#########################################################################
##                                                                     ##
##  I N T E R S T E L L A R   C O N S O L E                            ##
##            Copyright (C) 2025- Misato Observatory, Wakayama, Japan  ##
##                                                                     ##
##  This software is available under the GPL (General Public License)  ##
##                                                                     ##
#########################################################################

#
# Procedures for handling OS-dependent processes.
#
source system-proc.tcl


####################################################################
##                                                                ##
##                    L O C A L   C O N F I G                     ##
##                                                                ##
####################################################################

# default LANG for ISC
set isc_lang "ja"

#
# Read LANG
#
if { [catch {open "isc-lang.txt" r} fid] } {
  # do nothing
} else {
  while { [gets $fid line] >= 0 } {
    set s [string tolower [string trim $line]]
    if { [string length $s] != 0 && [string index $s 0] ne "#" } {
      set isc_lang_full $s
      set isc_lang [string range $isc_lang_full 0 1]
    }
  }
  catch {close $fid}
}

# Overwitten isc_lang by command args such as '-lang en'
set flg_lang 0
for {set i 0} {$i < $argc} {incr i} {
  set arg [lindex $argv $i]
  if { $arg eq "-lang" } {
    set flg_lang 1
  } elseif { $flg_lang != 0 } {
    set isc_lang $arg
    set flg_lang 0
  }
}

if { $isc_lang eq "ja" } {
  source -encoding $TCLSRC_ENCODING transl.ja.tcl
} else {
  source -encoding $TCLSRC_ENCODING transl.en.tcl
}

#
# Text Editor, Font Name, Flag
#
set os_name [get_os_name]

# default
set button_border 1
set label_border 1
set entry_border 1

if { $isc_lang eq "ja" } {
  # for 2-bytes locale
  array set fsz_table {
    SZ10 10
    SZ12 12
    SZ14 14
    SZ15 15
    SZ16 16
    SZ20 20
  }
} else {
  # for 1-byte locale
  array set fsz_table {
    SZ10 9
    SZ12 11
    SZ14 13
    SZ15 14
    SZ16 15
    SZ20 18
  }
}

#set font_list [font families]

# Large GUI で IPAGothic を使う場合に 1 をセット
# (IPAGothic がインストールされていなければMS Gothicが使われる)
set flag_use_ipagothic_large_gui_on_windows 0

if { $os_name eq "Darwin" } {
  # MacOS
  set text_editor "open -a TextEdit"
  if { $isc_lang eq "ja" } {
    set gui_font_name "IPAGothic"
  } else {
    set gui_font_name "Monaco"
  }
  set flag_available_exec 1
} elseif { [string range $os_name 0 6] eq "Windows" } {
  # Windows
  set text_editor "notepad.exe"
  if { $isc_lang eq "ja" } {
    set gui_font_name "MS Gothic"
    set button_border 2
    set label_border 2
    if { $flag_use_ipagothic_large_gui_on_windows != 0 } {
      # Test IPAGothic
      set s0 [font actual {{IPAGothic} 10}]
      set s1 [string range $s0 8 10]
      if { $s1 eq "IPA" } {
        set large_gui_font_name "IPAGothic"
        set fsz_table(SZ16) 16
        set fsz_table(SZ20) 19
        set large_button_border 1
        set large_label_border 2
      }
    }
  } else {
    set gui_font_name "Consolas"
    set button_border 1
    set label_border 0
  }
  set flag_available_exec 1
} elseif { $os_name eq "Android" } {
  # Android
  set text_editor "emacs"
  set gui_font_name "IPAGothic"
  set flag_available_exec 0
} else {
  # Other OS
  set text_editor "emacs"
  set gui_font_name "IPAGothic"
  set flag_available_exec 1
}

#             #
# GUI Setting #
#             #

#
# Returns the scaling factor of Windows.  Returns 100 when 100%.
#
# Following is a part of tk9.0 / 9.0.1-3 / library / scaling.tcl.
# Note that lines for X11 were deleted.
#
# Copyright (C) 2022 Csaba Nemethi <csaba.nemethi@t-online.de>
# See license.terms in Tk original source package.
#
proc get_scaling_pct {} {

    set pct [expr {[tk scaling] * 75}]

    #
    # Save the value of pct rounded to the nearest multiple
    # of 25 that is at least 100, in the variable scalingPct.
    # See "man n tk_scalingPct" for use of ::tk::scalingPct.
    #
    variable scalingPct
    for {set scalingPct 100} {1} {incr scalingPct 25} {
	if {$pct < $scalingPct + 12.5} {
	    break
	}
    }

    return $scalingPct
}

#
# scaling factor of Windows Desktop
#
set windows_scaling_pct [get_scaling_pct]


#
# Returns scaled pixel value.
#
proc scaled_px { px_in } {

  global windows_scaling_pct

  return [expr int(0.49 + $px_in * ($windows_scaling_pct / 100.0))]

}

#
# Returns scaled pixel value for thick border of button and labelframe.
#
proc scaled_thick_border { px_in } {

  global windows_scaling_pct

  return [expr 1 + int(0.49 + ($px_in - 1.0) * ($windows_scaling_pct / 100.0))]

}

#
# Returns scaled pixel value.
# (not used)
#
proc scaled_rgb { px_in r_in g_in b_in } {

  global windows_scaling_pct

  set px_int [scaled_px $px_in]
  set px_float [expr $px_in * ($windows_scaling_pct / 100.0)]
  set px_factor [expr $px_float / (1.0 * $px_int)]

  set r_out [expr int(1.0 * $r_in * $px_factor)]
  if { $r_out < 0 } {
    set r_out 0
  } elseif { 255 < $r_out } {
    set r_out 255
  }
  set g_out [expr int(1.0 * $g_in * $px_factor)]
  if { $g_out < 0 } {
    set g_out 0
  } elseif { 255 < $g_out } {
    set g_out 255
  }
  set b_out [expr int(1.0 * $b_in * $px_factor)]
  if { $b_out < 0 } {
    set b_out 0
  } elseif { 255 < $b_out } {
    set b_out 255
  }

  return [format "#%02x%02x%02x" $r_out $g_out $b_out]

}

#
# Returns scaled padding in Tcl list.
#
#  pad_x_in: pad_right + pad_left at 100% scaling
#  pad_y_in: pad_top + pad_bottom at 100% scaling
#
proc scaled_padding { pad_x_in pad_y_in } {

  global windows_scaling_pct
  global isc_lang

  set os_name [get_os_name]

  if { $os_name eq "Darwin" } {
    set pad_x $pad_x_in
    if { $isc_lang eq "ja" } {
      set pad_y $pad_y_in
    } else {
      # MacOS always uses TTK widgets... make padding smaller
      set pad_y [expr round($pad_y_in * 0.50)]
    }
  } elseif { [string range $os_name 0 6] eq "Windows" } {
    set pad_x [expr round($pad_x_in * ($windows_scaling_pct / 100.0))]
    set pad_y [expr round($pad_y_in * ($windows_scaling_pct / 100.0))]
  } else {
    set pad_x $pad_x_in
    set pad_y $pad_y_in
  }
  

  set pad_right [expr $pad_x / 2]
  set pad_left [expr $pad_right + ($pad_x % 2)]

  set pad_bottom [expr $pad_y / 2]
  set pad_top [expr $pad_bottom + ($pad_y % 2)]

  return [list $pad_left $pad_top $pad_right $pad_bottom]

}

#
# Font and Color for base, and font size of Dialog
#
set fontsize_startup $fsz_table(SZ16)
option add *font [list $gui_font_name $fontsize_startup]
set font_small [list $gui_font_name $fontsize_startup]
set font_splash [list $gui_font_name $fsz_table(SZ14)]

option add *background "#000000"
option add *foreground "#ff5050"
option add *activeBackground "#c08000"

option add *Entry.background "#303030"
option add *Entry.foreground "#ffe000"
option add *Entry.insertForeground "#000000"
option add *Entry.insertBackground "#00ff00"
option add *Entry.selectForeground "#ffffc0"
option add *Entry.selectBackground "#a01010"
option add *Entry.disabledBackground "#000000"
option add *Entry.disabledForeground "#ff6060"
option add *Text.foreground "#ff7030"
option add *Text.selectForeground "#ffc0c0"
option add *Text.selectBackground "#a01010"
option add *Text.insertForeground "#000000"
option add *Text.insertBackground "#00ff00"
set editor_foreground "#ff9060"

option add *Entry.borderWidth [scaled_px $entry_border]
option add *Text.borderWidth [scaled_px 1]
option add *Text.padX [scaled_px 1]
option add *Text.padY [scaled_px 1]
option add *Label.borderWidth [scaled_px $label_border]
option add *Label.padX [scaled_px 1]
option add *Label.padY [scaled_px 1]
#option add *Labelframe.relief raised
option add *Labelframe.borderWidth [scaled_thick_border 2]
option add *Labelframe.padX [scaled_px 2]
option add *Labelframe.padY [scaled_px 2]
option add *Frame.borderWidth 0
option add *Frame.padX 0
option add *Frame.padY 0
option add *Panedwindow.borderWidth [scaled_px 1]
option add *Panedwindow.sashWidth [scaled_px 4]
option add *Panedwindow.padX 0
option add *Panedwindow.padY 0
option add *Panedwindow.opaqueResize "0"

# valid for non-MacOS
option add *Button.background "#383838"
option add *Button.foreground "#ff6060"
option add *Button.borderWidth [scaled_thick_border $button_border]
option add *Button.padX 0
option add *Button.padY 0
# not used
option add *Dialog.msg.wrapLength "300p"

# This is for Dialog.
# When the Enter key is pressed on a focused button 
# (which can be cycled by pressing the Tab key), 
# it is treated as if it was clicked.
#bind Button <Return> { %W invoke }

# See https://wiki.tcl-lang.org/page/Changing+Widget+Colors
ttk::style theme use default

ttk::style configure TButton -foreground "#ff6060" -background "#383838" -focuscolor "#9a3030"
ttk::style configure TCheckbutton -foreground "#ff5050" -background "#000000" -indicatorcolor "#383838" -focuscolor "#9a3030"
ttk::style map TCheckbutton -indicatorcolor [list selected "#e0a000" pressed "#e0a000"]
ttk::style configure TCombobox -fieldbackground "#303030" -foreground "#ff5050" -background "#505050"
ttk::style configure TCombobox -arrowcolor "#ffe000" -selectforeground "#ff5050" -selectbackground "#000000"
ttk::style map TCombobox -fieldbackground [list disabled "#101010" readonly "#101010"]
ttk::style configure TPanedwindow -background "#000000" -sashthickness [scaled_px 4]
ttk::style configure TEntry -foreground "#ffe000" -background "#303030" -fieldbackground "#303030" -selectforeground "#ffffc0" -selectbackground "#a01010" -insertcolor "#00ff00" -insertwidth 2
ttk::style map TEntry -background [list disabled "#000000" readonly "#000000"]
ttk::style map TEntry -fieldbackground [list disabled "#000000" readonly "#000000"]
ttk::style map TEntry -foreground [list disabled "#ff6060" readonly "#ff6060"]

# Background color when "mouse-over".
ttk::style map TButton -background [list active "#383838"]
ttk::style map TCheckbutton -background [list active "#000000"]
ttk::style map TCombobox -background [list active "#505050"]

option add *TCombobox*Listbox.selectBackground "#ff5050"
option add *TCombobox*Listbox.selectForeground "#000000"

ttk::style configure TButton -font [list $gui_font_name $fontsize_startup]
ttk::style configure TButton -borderwidth [scaled_thick_border $button_border] -width 0
# Padding of button is {left top right bottom}.
# Setting for compatible to non-ttk button widget.
#ttk::style configure TButton -padding {4 4 4 3}
ttk::style configure TButton -padding [scaled_padding 8 7]
ttk::style configure Small.TButton -font [list $gui_font_name $fontsize_startup]

ttk::style configure TEntry -font [list $gui_font_name $fontsize_startup]
ttk::style configure TCheckbutton -font [list $gui_font_name $fontsize_startup]
ttk::style configure TCheckbutton -indicatordiameter [scaled_px $fontsize_startup] -borderwidth [scaled_px 1]
ttk::style configure TCombobox -borderwidth [scaled_px 1]


#
# ボタンウィジェット作成用 wrapper proc
# MacOS のボタンがダメダメな件の対策
#

# ttkのbuttonを使う場合は1
if { $os_name eq "Darwin" } {
  set flag_using_ttk_button 1
} else {
  set flag_using_ttk_button 0
}

#
# ボタンの作成 (ノーマルサイズ)
#
proc create_button { arg_id arg_text arg_command } {

  global flag_using_ttk_button
  set width_val 0

  # "," の後ろにボタン幅指定があればそれを拾う
  set elms [split $arg_text ","]
  set len_elms [llength $elms]
  set text_val [lindex $elms 0]
  if { 1 < $len_elms } {
    set width_val [lindex $elms 1]
  }

  if { $flag_using_ttk_button == 0 } {
    # 通常のボタンを使用する (MacOSだと色が壊れる)
    if { $width_val != 0 } {
      button $arg_id -width $width_val -text $text_val -command $arg_command
    } else {
      button $arg_id -text $text_val -command $arg_command
    }
  } else {
    # ttkのボタンを使用する (MacOSでもOK)
    if { $width_val != 0 } {
      ttk::button $arg_id -width $width_val -text $text_val -command $arg_command
    } else {
      ttk::button $arg_id -text $text_val -command $arg_command
    }
  }

}

#
# ボタンの作成 (smallサイズ)
#
proc create_button_small { arg_id arg_text arg_command } {

  global flag_using_ttk_button
  global font_small
  set width_val 0

  # "," の後ろにボタン幅指定があればそれを拾う
  set elms [split $arg_text ","]
  set len_elms [llength $elms]
  set text_val [lindex $elms 0]
  if { 1 < $len_elms } {
    set width_val [lindex $elms 1]
  }

  if { $flag_using_ttk_button == 0 } {
    # 通常のボタンを使用する (MacOSだと色が壊れる)
    if { $width_val != 0 } {
      button $arg_id -font $font_small -width $width_val -text $text_val -command $arg_command
    } else {
      button $arg_id -font $font_small -text $text_val -command $arg_command
    }
  } else {
    # ttkのボタンを使用する (MacOSでもOK)
    if { $width_val != 0 } {
      ttk::button $arg_id -style "Small.TButton" -width $width_val -text $text_val -command $arg_command
    } else {
      ttk::button $arg_id -style "Small.TButton" -text $text_val -command $arg_command
    }
  }

}

