#!/bin/sh
# the next line restarts using wish\
exec wish "$0" "$@"
# PFotos 1.5.2 Copyright(C) 2017-2025 Cora Kohlmeier, Frank Hamberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

#For details see License Button.

global pfotosversion exifversion tclversion
###############################################
set pfotosversion 1.5
###############################################
# if new tcl sources shall recognised, set the variable compile to 1
set compile 1
###############################################
global pfotoshome iconpath datahome home exiftool
global langstring langlist language lang
global DOS openexplorer
global dataname imageviewer env_ok
global defaulticonsize
global iflash
global widgetindex widgetlist widgetwindow selectionwindow
global bg abg fg tf bf sf dfg bfg
global toollist
global bincamera binlens binflash binwidth windowframelist
global wmwidth wmheight start_histogram

set pwd [pwd]
set home $env(HOME)
set datahome ""
set dataname ""
set language ""

##########################################################################
##########################################################################
# Betriebssystem ermitteln

# Default ist Linux
set DOS 0
set pfotoshome [file dir [info script]]
set iconpath $pfotoshome/info
set helpfile $iconpath/pfotos.pdf
set pfotosrcs $home/.local/PFotos

set tclversion [info tclversion]
#set opencommand /usr/bin/xdg-open
set openexplorer /usr/bin/xdg-open
set showhelp "/usr/bin/xdg-open $helpfile &"

set arch [lindex $tcl_platform(os) 0]
if {[string match Windows* $arch]==1} {
	set DOS 1
    set pfotoshome .
    set iconpath $pfotoshome/info
    set helpfile $iconpath/pfotos.pdf
    set openexplorer [file nativename  $pfotoshome/bat/openexplorer.bat]
	set pfotosrcs $home
	set showhelp "[auto_execok [file nativename $pfotoshome/bat/showhelp.bat]] $helpfile"
}
if {[string match Darwin* $arch]==1} {
	set DOS 2
    set pfotoshome [file dir [info script]]
    set openexplorer open
	set showhelp "open $helpfile &"
#	set exiftool /usr/local/bin/exiftool
	set pfotosrcs $home/Library/Application\ Support/PFotos
# auf MacOS mit Rosetta prüfen	
	if {$tcl_platform(machine) eq "x86_64"} {set DOS 3}
	if {$tcl_platform(machine) eq "arm64"} {set DOS 4}
	
}
if {$DOS!=1 && ![file exist $pfotosrcs]} {file mkdir $pfotosrcs}

##########################################################################
lappend auto_path $pfotoshome/tcllib
#lappend auto_path /opt/homebrew/opt/tcl-tk@8/lib/tcllib

package require Tk
package require cksum

set dirlist "tclsrc"

foreach item $dirlist {

if {$compile==1} {auto_mkindex $pfotoshome/$item *.tcl}
  lappend autopath $pfotoshome/$item

  set dir $pfotoshome/$item
  set unit [open $pfotoshome/$item/tclIndex]
  eval [read $unit]
  close $unit
}

if {$DOS==0} {
# Preparing fileboxes (not necessary but nice for hidden files)
   catch { tk_getOpenFile -w00t } ;# start file dialog with unknown option
       set ::tk::dialog::file::showHiddenBtn 1 
       set ::tk::dialog::file::showHiddenVar 0
    
} 

################################################################################
# Prepare package tkImg -- not in tcl/tk standard package for MacOS and Windows
# for Linux tkimg can be installed from standard repositories but it is provided 
# within this package
#################################################################################

if {[catch {package require Img}]} {
	switch $DOS {
		0 { set tkimgdir $pfotoshome/tkimg/Img-Linux64 } 
		1 { set tkimgdir $pfotoshome/tkimg/Img-win64 }
		2 { set tkimgdir $pfotoshome/tkimg/Img-Darwin64 }
		4 { set tkimgdir $pfotoshome/tkimg/Img-homebrew }
	  }
if {$compile==1} {auto_mkindex $tkimgdir *.tcl}
      lappend autopath $tkimgdir
      set dir $tkimgdir
      source "$tkimgdir/pkgIndex.tcl"   
      package require Img
}
if {[catch {package require BWidget}]} {
    set bwidgetdir $pfotoshome/bwidget
if {$compile==1} {auto_mkindex $bwidgetdir *.tcl}
      lappend autopath $bwidgetdir
      set dir $bwidgetdir
      source "$bwidgetdir/pkgIndex.tcl"   
      package require BWidget
}

##########################################################################

set buttonwidth 15
set smallbuttonwidth 10
# Indexliste für Anzeigespalten aufbauen
set widgetlist ""
lappend widgetlist "imgname" "cameras" "lenses" "focallength35" "aperture" "iso" "exposure" "flash" "focallength" "type" "daytime"
# Enumeration für Filter und Anzeigespalten
set i 0
foreach item $widgetlist {
	set widgetindex([lindex $widgetlist $i]) $i
	set widgetwindow([lindex $widgetlist $i],1) 1
	set widgetwindow([lindex $widgetlist $i],2) 1
	incr i
}	
# Presets einlesen
lang
setVars
#
# Sprache festlegen
# wenn noch keine Sprache in preferences festgelegt wurde, dann Umgebungsvariable auswerten, wenn es die denn gibt. 
# Falls nicht --> Windows, wird english gesetzt 
if ![info exist language] {
	if [info exist $env(LANG)] { set lang [string range $env(LANG) 0 1]} else {set lang en}
} else {
	set lang $language
}
# jetzt noch überprüfen, ob jemand von Hand eine nicht unterstützte Sprache eingestellt hat
# und im Zweifel $loc==0 auf englisch setzen
set loc 0
foreach lg $langlist {
	if {$lg==$lang} {set loc 1}
}
if {$loc==0} {set lang en}

# Exiftool Version bestimmen   
set exifversion $langstring(unknown,$lang)
if {[file exist $exiftool] && $exiftool!=""} { 
   if {$DOS!=1} {
		set command "exec [file nativename $exiftool] -ver"
		catch $command exifversion
   } else {
        set exiftool [file nativename $exiftool]
		set command [list exec {*}[auto_execok [file nativename $pfotoshome/bat/exiftoolversion.bat]] $exiftool]
		catch $command result
		set exifversion [lindex $result end]
   }
}   

# Schriftfarbe für die X-Fileselectboxes
# hier hart unabhängig vom Farbschema setzen, da der Fileselect-Hintergrund weiß ist 
#option add *foreground #303030
option add *foreground #000000


if { [llength $argv]>0 } {extractExifs $argv}
##########################################################################

set toollist "histogram1 histogram2 preferences license help tatze"
set bincamera ""
set binlens ""
set filterlist ""
set scalefactor [expr $fs/10.0]
if {$scalefactor > 1.0} {set scalefactor [expr 1.05 * $scalefactor]}
switch $DOS {
    1 {
        set binwidth([lindex $widgetlist 1]) [expr int($scalefactor * 450)];# Cameras
        set binwidth([lindex $widgetlist 2]) [expr int($scalefactor * 550)];# Lenses
        set binwidth([lindex $widgetlist 3]) [expr int($scalefactor * 300)];# Focal Length 35mm
        set binwidth([lindex $widgetlist 4]) [expr int($scalefactor * 300)];# Aperture
        set binwidth([lindex $widgetlist 5]) [expr int($scalefactor * 300)];# ISO
        set binwidth([lindex $widgetlist 6]) [expr int($scalefactor * 300)];# Exposure Time
        set binwidth([lindex $widgetlist 7]) [expr int($scalefactor * 300)];# Flash
        set binwidth([lindex $widgetlist 8]) [expr int($scalefactor * 300)];# Focal Length
        set binwidth([lindex $widgetlist 9]) [expr int($scalefactor * 200)];# Type
    	set binwidth([lindex $widgetlist 10]) [expr int($scalefactor * 300)];# Time of Day
    } 
    2 {
        set binwidth([lindex $widgetlist 1]) [expr int($scalefactor * 300)];# Cameras
        set binwidth([lindex $widgetlist 2]) [expr int($scalefactor * 350)];# Lenses
        set binwidth([lindex $widgetlist 3]) [expr int($scalefactor * 250)];# Focal Length 35mm
        set binwidth([lindex $widgetlist 4]) [expr int($scalefactor * 250)];# Aperture
        set binwidth([lindex $widgetlist 5]) [expr int($scalefactor * 250)];# ISO
        set binwidth([lindex $widgetlist 6]) [expr int($scalefactor * 250)];# Exposure Time
        set binwidth([lindex $widgetlist 7]) [expr int($scalefactor * 250)];# Flash
        set binwidth([lindex $widgetlist 8]) [expr int($scalefactor * 250)];# Focal Length
        set binwidth([lindex $widgetlist 9]) [expr int($scalefactor * 150)];# Type
    	set binwidth([lindex $widgetlist 10]) [expr int($scalefactor * 250)];# Time of Day
    } 
    default {
	set binwidth([lindex $widgetlist 1]) [expr int($scalefactor * 400)];# Cameras
	set binwidth([lindex $widgetlist 2]) [expr int($scalefactor * 500)];# Lenses
	set binwidth([lindex $widgetlist 3]) [expr int($scalefactor * 250)];# Focal Length 35mm
	set binwidth([lindex $widgetlist 4]) [expr int($scalefactor * 250)];# Aperture
	set binwidth([lindex $widgetlist 5]) [expr int($scalefactor * 250)];# ISO
	set binwidth([lindex $widgetlist 6]) [expr int($scalefactor * 250)];# Exposure Time
	set binwidth([lindex $widgetlist 7]) [expr int($scalefactor * 200)];# Flash
	set binwidth([lindex $widgetlist 8]) [expr int($scalefactor * 250)];# Focal Length
	set binwidth([lindex $widgetlist 9]) [expr int($scalefactor * 200)];# Type
	set binwidth([lindex $widgetlist 10]) [expr int($scalefactor * 300)];# Time of Day
    }
}
set windowframelist ""
set iflash -1

ReadFile $dataname

wm geometry . "$wmwidth\x$wmheight\+0+30"

wm title . "Tiger Graphics PFotos"

wm iconmask . @$iconpath/tinylogo.pic
wm iconbitmap . @$iconpath/tinylogo.pic
# für das Apple-Dock noch ein schönes Icon bauen
if {$DOS>=2} {
   image create photo PFotosIcon -file $iconpath/PFotosAppIcon.gif
   wm iconphoto . -default PFotosIcon
}   
wm protocol . WM_DELETE_WINDOW {writedefaults;exit}
# hier wird die Veränderung der Fenstergröße überwacht und die Scrolleable-Bereiche angepasst
bind . <Configure> {
    if {"%W" eq [winfo toplevel %W]} {
        if {($wmheight != %h) || ($wmwidth != %w)} {
        set wmheight %h
        set wmwidth %w
        writedefaults
        resize $windowframelist $wmheight
    }
}
}
bind . <Enter> {
         resize $windowframelist $wmheight
}

menubar
#set Menu1 [menu .menubar.mMenu1 -tearoff 0]
#.menubar add cascade -label Eintrag1 -menu .menubar.mMenu1
#Buttonframe

set c .top
frame $c -borderwidth 10 -bg $bg
pack $c -side top -fill x
button $c.extractExifs -width $buttonwidth -text $langstring(extract,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {extractExifs; restoreHist}
button $c.openfile -width $buttonwidth -text $langstring(open,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {OpenFile 1; restoreHist}
button $c.histogram1 -width $buttonwidth -text $langstring(camslenses,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {set start_histogram 1; makeframe histogram1; eval histogram1; writedefaults}
button $c.histogram2 -width $buttonwidth -text $langstring(imagedata,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {set start_histogram 2; makeframe histogram2; eval histogram2; writedefaults}
button $c.preferences -width $buttonwidth -text $langstring(preferences,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {makeframe preferences; eval preferences}
button $c.license -width $buttonwidth -text $langstring(license,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {makeframe license; eval tatzetool license;}

button $c.help -width $smallbuttonwidth -text $langstring(help,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {exec {*}$showhelp}
button $c.about -width $smallbuttonwidth -text $langstring(about,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {makeframe tatze; eval tatzetool about}
button $c.exit -width $smallbuttonwidth -text $langstring(exit,$lang)  -font "-size $bfs" -bg $bg -fg $bfg -command {writedefaults;exit}

pack $c.extractExifs $c.openfile $c.histogram1 $c.histogram2 $c.preferences  \
     $c.license $c.help  $c.about  $c.exit  -side left -fill x
     
label $c.tatze -bitmap @$iconpath/tatze.xbm -fg $fg -bg $bg
pack  $c.tatze  -ipadx 20 -side left -fill x 

#Mainframe
frame .main  -borderwidth 10 -width $wmwidth -bg $bg
pack .main -fill both
update
update idletasks

if {$start_histogram==2} {
#   $c.histogram1 invoke
   $c.histogram2 invoke
} else {
#   $c.histogram2 invoke
   $c.histogram1 invoke
}

wm minsize . [winfo reqwidth .top] 120
# wenn aus den vorhergehendne Prüfungen die Toolumgebung in nicht Ordnung ist, wird in die Einstellung gesprungen, ansonsten
# ansonsten hier schon einmal alle Widgets aktualisieren, um eventuell aus vorheriger Sitzung 
# aktive Filter (ungültige Zeit, Ausschlüsse von Verzeichnissen, Dateiname und -typen anzuwenden. 
# excludenotime excludedirlist excludefilelist excludetypelist
if {$env_ok==0} { $c.preferences invoke } else {
	if {$excludenotime==1} {toggleValidTime}
	if {$excludefilelist==1} {toggleExcludeLists files}
	if {$excludetypelist==1} {toggleExcludeLists type}
	if {$excludedirlist==1} {toggleExcludeLists dir}
}
raise .
# jetzt das Fenster nach vorne zwingen, damit PFotos z.B. aus CaptureOne aufgerufen werden kann und auch nach vorne kommt
wm attributes . -topmost yes
update
update idletasks
# und nun das Fenster wieder der normalen Kontrolle übergeben, damit die eigenen Fenster und auch das Betriebssystem eine Chance haben
wm attributes . -topmost no
