pd.tk 266 KB
Newer Older
Miller Puckette's avatar
Miller Puckette committed
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/wish
# Copyright (c) 1997-1999 Miller Puckette.
# For information on usage and redistribution, and for a DISCLAIMER OF ALL
# WARRANTIES, see the file, "LICENSE.txt," in this distribution.

# changed by Thomas Musil 09.2001
# between "pdtk_graph_dialog -- dialog window for graphs"
# and "pdtk_array_dialog -- dialog window for arrays"
# a new dialogbox was inserted, named:
# "pdtk_iemgui_dialog -- dialog window for iem guis"
#
12
# all these changes are labeled with #######iemlib########
Miller Puckette's avatar
Miller Puckette committed
13

Miller Puckette's avatar
Miller Puckette committed
14
# set pd_nt (bad name) 0 for unix, 1 for microsoft, and 2 for Mac OSX.
15
16
17
18
19

#May 22 2009
#GUI improvements and dynamic runtime 8.5 widget upgrade for Linux by Ivica Ico Bukvic
#http://ico.bukvic.net <ico@vt.edu>

20
21
#puts stderr [info tclversion]

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
if { [info tclversion] >= 8.5 } {

	# EDIT THIS PART TO CUSTOMIZE LINUX THEME
	# match gnome colors
	# Ubuntu Human
	set linux_wm_bgcolor "#e5e5e5"
	# set linux_wm_hlcolor "#fdbf69"
	set linux_wm_hlcolor "#f9ba81"

	# ttk colors
	# -frame, -lighter, and -selectbg are automatically
	#	replaced by theme colors specified above
	variable colors
	array set colors {
		-frame 		"#e5e5e5"
		-window		"#ffffff"
		-darkest 	"#999999"
		-darker 	"#709970"
		-dark		"#a8e6a8"
		-light		"#d2ffd2"
		-lighter 	"#e5e5e5"
		-disabledfg	"#a3a3a3"
		-selectbg	"#fdbf69"
		-selectfg	"#000000"
	}
	# STOP EDITING BEYOND THIS POINT

	#sync ttk with theme choice above it
	set colors(-frame) $linux_wm_bgcolor
	set colors(-lighter) $linux_wm_bgcolor
	set colors(-selectbg) $linux_wm_hlcolor

	ttk::style theme create purty_linux -parent clam -settings {

		ttk::style configure "." \
			-background 	$colors(-frame) \
			-foreground 	black \
			-bordercolor	$colors(-darkest) \
			-selectbackground 	$colors(-selectbg) \
			-selectforeground 	$colors(-selectfg) \
			-troughcolor	$colors(-dark) \
			-arrowcolor 	$colors(-darkest) \
			-font 		TkDefaultFont \
			;

		ttk::style map "." -background \
			[list disabled $colors(-frame)  active $colors(-lighter)] ;
		ttk::style map "." -foreground [list disabled $colors(-disabledfg)] ;
		    ttk::style map "." -embossed [list disabled 0] ;

		ttk::style configure TButton \
			-anchor center -width -11 -padding "1 1" \
			-relief raised -shiftrelief 1 \
			-highlightthickness 1 -highlightcolor $colors(-selectbg)

		ttk::style map TButton -relief {
			{pressed !disabled} 	sunken
			{active !disabled} 	raised
		} -highlightcolor {alternate black}

		ttk::style configure TCheckbutton \
			-indicatorcolor $colors(-window) -padding 2
		ttk::style configure TRadiobutton \
			-indicatorcolor $colors(-window) -padding 2
		ttk::style map TCheckbutton -indicatorcolor \
			[list  disabled $colors(-frame)  pressed $colors(-frame)]
		ttk::style map TRadiobutton -indicatorcolor \
			[list  disabled $colors(-frame)  pressed $colors(-frame)]

		ttk::style configure TMenubutton \
			-width -11 -padding "3 3" -relief raised

		ttk::style configure TEntry \
			-padding 1 -fieldbackground $colors(-window) ;
		ttk::style map TEntry -fieldbackground \
			[list readonly $colors(-frame) disabled $colors(-frame)]
		ttk::style configure TCombobox \
			-padding 1 -fieldbackground $colors(-window) ;
		ttk::style map TCombobox -fieldbackground \
			[list readonly $colors(-frame) disabled $colors(-frame)]

		ttk::style configure Toolbutton -relief flat -padding 2
		ttk::style map Toolbutton -relief \
			{disabled flat selected sunken pressed sunken active raised}
		ttk::style map Toolbutton -background \
			[list pressed $colors(-dark)  active $colors(-light)]

		ttk::style configure TScrollbar -relief raised
		ttk::style configure TScale \
			-groovewidth 4 -troughrelief sunken \
			-sliderwidth raised -borderwidth 2
		ttk::style configure TProgressbar \
			-background $colors(-selectbg) -borderwidth 0

		ttk::style configure TLabelframe -relief groove -borderwidth 2

		ttk::style configure TNotebook -tabmargins {2 2 1 0}
		ttk::style configure TNotebook.Tab \
			-padding {4 2} -background $colors(-dark)
		ttk::style map TNotebook.Tab \
			-background [list selected $colors(-frame)] \
			-expand [list selected {2 2 1 0}] \
			;

		ttk::style configure Treeview -fieldbackground $colors(-window)
		ttk::style configure Heading -font TkHeadingFont -relief raised
		ttk::style configure Row -background $colors(-window)
		ttk::style map Row \
			-background [list selected $colors(-selectbg)]
		ttk::style map Item \
			-foreground [list selected $colors(-selectfg)]
		ttk::style map Cell \
			-foreground [list selected $colors(-selectfg)]
	}
}

# Automate matching of the linux wm and use ttk where possible
# As of right now it is only enabled if system is Linux/Unix using tcl >= 8.5
proc match_linux_wm {list} {
	global pd_nt linux_wm_bgcolor linux_wm_hlcolor
	if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
		if {[lsearch -regexp $list ::] == -1} {
			if {[lindex $list 0] != "button" \
				&& [lindex $list 0] != "checkbutton" \
				&& [lindex $list 0] != "radiobutton" \
				&& [lindex $list 0] != "entry" \
				&& [lindex $list 0] != "scrollbar"} { 
					lappend list -bg $linux_wm_bgcolor
			}
			if {[lindex $list 0] == "listbox" \
				|| [lindex $list 0] == "text"} {

				lappend list -bg white -highlightcolor $linux_wm_hlcolor
			}
			if {[lindex $list 0] == "menu"} {
	
				lappend list -activebackground $linux_wm_hlcolor -bd 0
			}
			#convert non-ttk objects to ttk objects
			if {[lindex $list 0] == "button" \
				|| [lindex $list 0] == "checkbutton" \
				|| [lindex $list 0] == "radiobutton" \
				|| [lindex $list 0] == "entry" \
				|| [lindex $list 0] == "scrollbar"} { 
				set newlist [lreplace $list 0 0 ttk::[lindex $list 0]]
			}
		}
	}
	if {[info exists newlist]} {
		eval $newlist
	} else {
		eval $list
	}
}

Miller Puckette's avatar
Miller Puckette committed
177
178
if { $tcl_platform(platform) == "windows" }  {
    set pd_nt 1
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
179
    set ctrl_key "Control"
180
    # fontsc
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
181
    set defaultFontFamily {DejaVu Sans Mono}
182
    font create menuFont -family Tahoma -size 10
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    # mouse cursors
    set cursor_runmode_nothing "arrow"
    set cursor_runmode_clickme "right_ptr"
    set cursor_runmode_thicken "sb_v_double_arrow"
    set cursor_runmode_addpoint "plus"
    set cursor_editmode_nothing "hand2"
    set cursor_editmode_connect "circle"
    set cursor_editmode_disconnect "X_cursor"
	# set file types that open/save recognize
	set filetypes {
		{{Pd Files}         {.pd}  }
		{{Max Patch Files}  {.pat} }
		{{Max Text Files}   {.mxt} }
		{{Max Binary Files} {.mxb} }
		{{Max Help Files}   {.help} }
	}
	# use CommonProgramFiles by default instead because its a lot easier to
	# find. Microsoft seems to have carefully hidden the AppData folder from
	# all but the most determined users.
	#set externalsdir "$::env(AppData)/Pd"
	set externalsdir "$::env(CommonProgramFiles)/Pd"
Miller Puckette's avatar
Miller Puckette committed
204
205
} elseif { $tcl_platform(os) == "Darwin" } {  
    set pd_nt 2
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
206
207
	set ctrl_key "Mod1"
    # fonts
Miller Puckette's avatar
Miller Puckette committed
208
    set defaultFontFamily Monaco
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    # mouse cursors
    set cursor_runmode_nothing "arrow"
    set cursor_runmode_clickme "center_ptr"
    set cursor_runmode_thicken "sb_v_double_arrow"
    set cursor_runmode_addpoint "plus"
    set cursor_editmode_nothing "hand2"
    set cursor_editmode_connect "circle"
    set cursor_editmode_disconnect "X_cursor"
	# set file types that open/save recognize
	set filetypes {
		{{Pd Files}                {.pd}  }
		{{Max Patch Files (.pat)}  {.pat} }
		{{Max Text Files (.mxt)}   {.mxt} }
		{{Max Binary Files (.mxb)} {.mxb} }
		{{Max Help Files (.help)}  {.help} }
	}
	set externalsdir "$::env(HOME)/Library/Pd"
Miller Puckette's avatar
Miller Puckette committed
226
} else { 
227
228
	# set nicer theme
	ttk::style theme use purty_linux
229
	clipboard clear
230
	set window_prefs {}
Miller Puckette's avatar
Miller Puckette committed
231
    set pd_nt 0
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
232
    set ctrl_key "Control"
233
234
235
	# Ctrl modifier
	set ctrl_l_down 0
	set ctrl_r_down 0
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
236
237
238
239
240
241
242
243
    # fonts
    set defaultFontFamily {DejaVu Sans Mono}
    # mouse cursors
    set cursor_runmode_nothing "left_ptr"
    set cursor_runmode_clickme "right_ptr"
    set cursor_runmode_thicken "sb_v_double_arrow"
    set cursor_runmode_addpoint "plus"
    set cursor_editmode_nothing "hand2"
244
    set cursor_editmode_connect "target"
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
245
246
247
248
249
250
251
252
253
254
    set cursor_editmode_disconnect "X_cursor"
	# set file types that open/save recognize
	set filetypes {
		{{pd files}         {.pd}  }
		{{max patch files}  {.pat} }
		{{max text files}   {.mxt} }
		{{max binary files} {.mxb} }
		{{max help files}   {.help} }
	}
	set externalsdir "$::env(HOME)/pd-externals"
Miller Puckette's avatar
Miller Puckette committed
255
256
}        

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# make sure the user folder for installing externals exists
catch {
	if { ! [file exists $externalsdir] && [file exists [file dirname $externalsdir]] } {
		puts stderr "Creating folder for user-installed externals: \n\t$externalsdir"
		file mkdir $externalsdir
	}
}


# namespace for general-purpose functions
proc pdtk_encode { listdata } {
    set outlist {}
    foreach this_path $listdata {
        if {0==[string match "" $this_path]} {
            lappend outlist [pdtk_encodedialog $this_path]
        }
    }
    return $outlist
}


# args is a list of length 1 or 2,
# specifying optional additional x, y offsets for the window
proc center_window { w args } {
    set offx 0
    set offy 0

    if { [llength $args] >= 2 } {
        set offx [lindex $args 0]
        set offy [lindex $args 1]
    }

    set x [expr [winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \
        - [winfo vrootx [winfo parent $w]] + $offx]
    set y [expr [winfo screenheight $w]/2 - [winfo reqheight $w]/2 \
        - [winfo vrooty [winfo parent $w]] + $offy]
    wm geom $w +$x+$y
}


Miller Puckette's avatar
Miller Puckette committed
297
298
299
# start Pd-extended font hacks -----------------------------

# Pd-0.39.2-extended hacks to make font/box sizes the same across platform
300
#puts stderr "tk scaling is [tk scaling]"
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
301
tk scaling 1
Miller Puckette's avatar
Miller Puckette committed
302
303

# this font is for the Pd Window console text
304
font create console_font -family $defaultFontFamily -size 9 -weight normal
Miller Puckette's avatar
Miller Puckette committed
305
# this font is for text in Pd windows
306
font create text_font -family $defaultFontFamily -size 9 -weight normal
Miller Puckette's avatar
Miller Puckette committed
307
# for text in Properties Panels and other panes
308
font create highlight_font -family $defaultFontFamily -size 9 -weight bold
Miller Puckette's avatar
Miller Puckette committed
309
310
311

# end Pd-extended font hacks -----------------------------

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# K-12 version global variable (enabled through -k12, disabled by default)
set k12_mode 0

# Only can be enabled at startup (cannot be toggled afterwards)
proc pdtk_enable_k12_mode {extra_dir} {
	global k12_mode
	global signal_cord_width
	global autotips
	global signal_cord_highlight
	global signal_cord

	set k12_mode 1
	set signal_cord_width 4
	set autotips 1
	set signal_cord_highlight "#474"
	set signal_cord "#2ca7d4"

	image create photo i.connect -file $extra_dir/K12/buttons/connect-on.png
	image create photo i.add -file $extra_dir/K12/buttons/add.png
	image create photo i.buttons -file $extra_dir/K12/buttons/buttons.png
	image create photo i.delay -file $extra_dir/K12/buttons/delay.png
	image create photo i.filter -file $extra_dir/K12/buttons/filter.png
	image create photo i.hit -file $extra_dir/K12/buttons/hit.png
	image create photo i.mapper -file $extra_dir/K12/buttons/mapper.png
	image create photo i.multiply -file $extra_dir/K12/buttons/multiply.png
	image create photo i.output -file $extra_dir/K12/buttons/audio-on.png
	image create photo i.pitch -file $extra_dir/K12/buttons/pitch.png
	image create photo i.reverb -file $extra_dir/K12/buttons/reverb.png
	image create photo i.short1 -file $extra_dir/K12/buttons/short1.png
	image create photo i.short2 -file $extra_dir/K12/buttons/short2.png
	image create photo i.sustained1 -file $extra_dir/K12/buttons/sustained1.png
	image create photo i.sustained2 -file $extra_dir/K12/buttons/sustained2.png
	image create photo i.speed -file $extra_dir/K12/buttons/speed.png
	image create photo i.edit -file $extra_dir/K12/buttons/edit.png
	image create photo i.perform -file $extra_dir/K12/buttons/perform.png
}

349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# calculate offset on a movable canvas
set tmp_xpix 0
set tmp_ypix 0

set popup_xpix 0
set popup_ypix 0

# monitor pointer position
set pointer_x_local 0
set pointer_y_local 0

set pointer_x_virtual 0
set pointer_y_virtual 0

set pointer_x_global 0
set pointer_y_global 0

# text pasting global
set copytexttocanvas 0

369
set global_clipboard 0
370
371
# used for comparison to avoid redundant copyfromexternalbuffer
set last_clipboard 0
372
373
set global_selection 0

374
375
376
377
378
379
380
#TOOLTIPS PATCH
#TODO: make a separate tcl file for tooltips and put
#afterid in its scope    
variable afterid 0
variable duplicate_tags -1
variable current_window 0
variable nlet_color 0
381
variable autotips 0
382
variable tooltip_visible 0
383

384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# x:y location tooltip during dragging
set tooltip [toplevel .tooltip -bd 1 -bg black]
wm attributes $tooltip -topmost 1
wm overrideredirect $tooltip 1
pack [label $tooltip.label -bg lightyellow -fg black -text aaa -justify left]
wm withdraw $tooltip

# timeout for the tooltip
proc pdtk_toggle_xy_tooltip {name num} {
	global tooltip
	if {$num == 0} {
		wm withdraw $tooltip
	} else {
		wm deiconify $tooltip
	}
}

proc pdtk_update_xy_tooltip {name x y} {
	global tooltip
	global pointer_x_virtual pointer_y_virtual pointer_x_global pointer_y_global
	wm geometry $tooltip +[expr $pointer_x_global+15]+[expr $pointer_y_global-2]
	$tooltip.label configure -text [concat x: $x\ny: $y]
	set pointer_x_virtual $x
	set pointer_y_virtual $y
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
410
411
412
413
414
415
416
417
418
419
420
421
# begin hack to hide hidden files/folder in tk browser on unix ----------
if {$pd_nt == 0} {
    # load the dialog once, otherwise setting the vars will not work
    catch {tk_getOpenFile -with-invalid-argument} 

    # change the environment variables
    namespace eval ::tk::dialog::file {
    variable showHiddenBtn 1
    variable showHiddenVar 0
    }
}
# end hidden files/folder hack ------------------
Miller Puckette's avatar
Miller Puckette committed
422

423
# Tearoff is set to false by default:
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
424
set pd_tearoff 0
425
426
# Put menu tearoff is set to true by default:
set put_tearoff 1
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
427
428
# turn off tearoff menus globally
#option add *tearOff 0
Miller Puckette's avatar
Miller Puckette committed
429
430
431
432
433
434
435
436

# jsarlo
set pd_array_listview_pagesize 1000
set pd_array_listview_id(0) 0
set pd_array_listview_entry(0) 0
set pd_array_listview_page(0) 0
# end jsarlo

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
437
438
439
# color scheme
set canvas_fill "white"
set text_color "#000"
440
set select_color "#e87216"
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
441
442
443
444
445
446
447
448
449
450
set dash_outline "#f00"
set dash_fill "#f7f7f7"
set box_outline "#ccc"
set graph_outline "#777"
set atom_box_fill "#eee"
set msg_box_fill "#f8f8f6"
set obj_box_fill "#f6f8f8"
set signal_cord_highlight "#58a"
set signal_cord "#808095"
set signal_nlet $signal_cord
451
set signal_cord_width 2
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
452
453
454
455
set msg_cord_highlight "#474"
set msg_cord "#565"
set msg_nlet "white"
set mixed_nlet "#88aaff"
456
set msg_cord_width 1
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
457

458
459
460
461
#nlet highlighting stuff
set select_nlet_color $select_color
set highlight_width 3

Miller Puckette's avatar
Miller Puckette committed
462
463
464
465
if {$pd_nt == 1} {
    global pd_guidir
    set pd_gui2 [string range $argv0 0 [expr [string last \\ $argv0 ] - 1]]
    regsub -all \\\\ $pd_gui2 / pd_gui3
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
466
    set pd_guidir [file normalize $pd_gui3/..]
Miller Puckette's avatar
Miller Puckette committed
467
468
469
470
    load $pd_guidir/bin/pdtcl.dll
}

if {$pd_nt == 2} {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
471
    # turn on James Tittle II's fast drawing
Miller Puckette's avatar
Miller Puckette committed
472
    set tk::mac::useCGDrawing 1
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
473
474
    # anti-alias all lines that need it
    set tk::mac::CGAntialiasLimit 0
Miller Puckette's avatar
Miller Puckette committed
475
476
    global pd_guidir
    set pd_gui2 [string range $argv0 0 [expr [string last / $argv0 ] - 1]]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
477
    set pd_guidir [file normalize $pd_gui2/..]
Miller Puckette's avatar
Miller Puckette committed
478
479
480
481
482
483
484
485
486
487
488
489
490
    load $pd_guidir/bin/libPdTcl.dylib
    global pd_macready
    set pd_macready 0
    global pd_macdropped
    set pd_macdropped ""
    # tk::mac::OpenDocument is called with the filenames put into the 
    # var args whenever docs are either dropped on the Pd.app icon or 
    # opened from the Finder.
    # It uses menu_doc_open so it can handles numerous file types.
    proc tk::mac::OpenDocument {args} {
        global pd_macready pd_macdropped
        foreach file $args {
            if {$pd_macready != 0} {
491
492
                pd [concat pd open [pdtk_enquote [file tail $file]] \
                        [pdtk_enquote  [file dirname $file]] \;]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
493
                menu_doc_open [file dirname $file] [file tail $file]
Miller Puckette's avatar
Miller Puckette committed
494
495
496
497
498
            } else {
                set pd_macdropped $args
            }
        }
    }
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
499
500
501
502
503
	# intercept kAEQuitApplication from Cmd-Q
	proc ::tk::mac::Quit {} {
		puts stderr "::tk::mac::Quit"
		menu_quit
	}
Miller Puckette's avatar
Miller Puckette committed
504
505
506
507
508
509
510
511
512
513
514
515
516
}

# hack so you can easily test-run this script in linux... define pd_guidir
# (which is normally defined at startup in pd under linux...)

if {$pd_nt == 0} {
    if {! [info exists pd_guidir]} {
        global pd_guidir
        puts stderr {setting pd_guidir to '.'}
        set pd_guidir .
    }
}

517
518
#set pd_deffont {courier 10}
set pd_deffont console_font
Miller Puckette's avatar
Miller Puckette committed
519
520
521

set help_top_directory $pd_guidir/doc

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
522
523
524
525
526
527
528
529
#==============================================================================#
# pd-gui-rewrite-0.43 help browser backport

# Pd's packages are stored in the same directory as the main script (pd-gui.tcl)
set auto_path [linsert $auto_path 0 [file dirname [info script]]]
# the pd-gui-rewrite-0.43 help browser is backported to Pd-extended 0.42
package require helpbrowser
package require msgcat
530
package require tkpng
Miller Puckette's avatar
Miller Puckette committed
531

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# official GNU gettext msgcat shortcut
proc _ {s} {return [::msgcat::mc $s]}

namespace eval ::pdwindow:: {
    proc verbose {level postme} {puts stderr "$level: $postme"}
    proc error {postme} {puts stderr $postme; pdtk_post $postme}
    proc warn {postme} {::pdwindow::error $postme}
}

set ::dialog_menubar .mbar
set ::modifier $ctrl_key
set ::sys_libdir $pd_guidir
switch $pd_nt {
    0 {set ::pd_path [list ~/pd-externals /usr/local/lib/pd-externals]}
    1 {set ::pd_path [list [file normalize $::env(AppData)/Pd] \
                          [file normalize $::env(CommonProgramFiles)/Pd]]}
    2 {set ::pd_path [list ~/Library/Pd /Library/Pd]}
}
#==============================================================================#
Miller Puckette's avatar
Miller Puckette committed
551
552
553
554
555

################## set up main window #########################
# the menus are instantiated here for the main window
# for the patch windows, they are created by pdtk_canvas_new

556
557
558
559
560
561
562
563
564
#ttk error button customizations
ttk::style configure IOErrorOn.TButton -background "#dd2222"
ttk::style map IOErrorOn.TButton -background [list active "#ff2222"] \
	-foreground [list disabled black]
ttk::style configure IOErrorOff.TButton -background lightgrey
ttk::style map IOErrorOff.TButton -background [list active $colors(-frame)]

match_linux_wm [list menu .mbar -relief flat]
match_linux_wm [list menu .mbar.file -tearoff $pd_tearoff]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
565
.mbar add cascade -label File -menu .mbar.file
566
match_linux_wm [list menu .mbar.edit -tearoff $pd_tearoff]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
567
.mbar add cascade -label Edit -menu .mbar.edit
568
match_linux_wm [list menu .mbar.put -tearoff $pd_tearoff]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
569
.mbar add cascade -label Put -menu .mbar.put
570
571
572
573
574
#match_linux_wm [list menu .mbar.find -tearoff $put_tearoff]
#.mbar add cascade -label Find -menu .mbar.find
match_linux_wm [list menu .mbar.windows -postcommand [concat pdtk_fixwindowmenu] \
	-tearoff $pd_tearoff]
match_linux_wm [list menu .mbar.audio -tearoff $pd_tearoff]
Miller Puckette's avatar
Miller Puckette committed
575
576
577
if {$pd_nt != 2} {
    .mbar add cascade -label "Windows" -menu .mbar.windows
    .mbar add cascade -label "Media" -menu .mbar.audio
578
    match_linux_wm [list menu .mbar.help -tearoff $pd_tearoff]
Miller Puckette's avatar
Miller Puckette committed
579
580
581
582
    .mbar add cascade -label "Help" -menu .mbar.help
} else {
    menu .mbar.apple -tearoff 0
    .mbar add cascade -label "Apple" -menu .mbar.apple 
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
583
    # arrange menus according to Apple HIG
Miller Puckette's avatar
Miller Puckette committed
584
585
    .mbar add cascade -label "Media" -menu .mbar.audio
    .mbar add cascade -label "Window" -menu .mbar.windows
586
    match_linux_wm [list menu .mbar.help -tearoff $pd_tearoff]
Miller Puckette's avatar
Miller Puckette committed
587
588
589
    .mbar add cascade -label "Help" -menu .mbar.help
}

Miller Puckette's avatar
Miller Puckette committed
590
591
592
# fix menu font size on Windows with tk scaling = 1
if {$pd_nt == 1} {
    .mbar.file configure -font menuFont
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
593
    .mbar.edit configure -font menuFont
Miller Puckette's avatar
Miller Puckette committed
594
595
596
597
598
599
    .mbar.find configure -font menuFont
    .mbar.windows configure -font menuFont
    .mbar.audio configure -font menuFont
    .mbar.help configure -font menuFont
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
600
601
proc showhide_printouttext {state} {
    if {$state} {
602
603
        #pack .printout -side bottom -fill both -expand 1
		#pack .controls.clr_console -pady 30
604
605
606
		wm deiconify .printout
		#wm resizable . 1 1
		#wm minsize . 460 194
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
607
    } else {
608
        #pack forget .printout
609
610
611
612
613
		wm withdraw .printout
		#pack forget .controls.clr_console
		#wm minsize . 0 0
		#wm geometry . 355x75
		#wm resizable . 0 0
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
614
615
616
    }
}

Miller Puckette's avatar
Miller Puckette committed
617
618
619
620
set ctrls_audio_on 0
set ctrls_meter_on 0
set ctrls_inlevel 0
set ctrls_outlevel 0
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
621
set show_text_window 0
Miller Puckette's avatar
Miller Puckette committed
622

623
624
625
626
match_linux_wm [list frame .controls]
if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
	ttk::separator .eyecandy
	pack .eyecandy .controls -fill x -expand 0
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
627
} else {
628
	pack .controls -fill x -expand 1
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
629
}
630
631
match_linux_wm [list frame .controls.switches]
match_linux_wm [list checkbutton .controls.switches.audiobutton -text {compute audio  } \
Miller Puckette's avatar
Miller Puckette committed
632
    -variable ctrls_audio_on \
633
    -command {pd [concat pd dsp $ctrls_audio_on \;]}]
Miller Puckette's avatar
Miller Puckette committed
634

635
match_linux_wm [list checkbutton .controls.switches.meterbutton -text {peak meters} \
Miller Puckette's avatar
Miller Puckette committed
636
    -variable ctrls_meter_on \
637
    -command {pd [concat pd meters $ctrls_meter_on \;]}]
Miller Puckette's avatar
Miller Puckette committed
638

639
match_linux_wm [list checkbutton .controls.switches.console -text "console" \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
640
    -variable show_console \
641
    -command {showhide_printouttext $show_console}]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
642

Miller Puckette's avatar
Miller Puckette committed
643
pack .controls.switches.audiobutton .controls.switches.meterbutton \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
644
    .controls.switches.console -side top -anchor w
Miller Puckette's avatar
Miller Puckette committed
645

646
647
648
649
650
651
652
653
654
655
656
657
658
659
match_linux_wm [list frame .controls.inout]
match_linux_wm [list frame .controls.inout.in]
match_linux_wm [list label .controls.inout.in.label -text IN]
entry .controls.inout.in.level -textvariable ctrls_inlevel -width 3 \
	-highlightthickness 0 -takefocus 0 -state readonly -readonlybackground white
if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
	match_linux_wm [list button .controls.inout.in.clip \
		-text {CLIP} -state disabled -style IOErrorOff.TButton -width 4]
} else {
	button .controls.inout.in.clip -text {CLIP} -state disabled
}

match_linux_wm [list frame .controls.inout.in.spacer]

Miller Puckette's avatar
Miller Puckette committed
660
pack .controls.inout.in.label .controls.inout.in.level \
661
662
663
664
665
666
667
668
669
670
671
672
673
674
    .controls.inout.in.clip .controls.inout.in.spacer -side top -pady 1

match_linux_wm [list frame .controls.inout.out]
match_linux_wm [list label .controls.inout.out.label -text OUT]
entry .controls.inout.out.level -textvariable ctrls_outlevel -width 3 \
	 -highlightthickness 0 -takefocus 0 -state readonly -readonlybackground white
if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
	match_linux_wm [list button .controls.inout.out.clip \
		-text {CLIP} -state disabled -style IOErrorOff.TButton -width 4]
} else {
	button .controls.inout.out.clip -text {CLIP} -state disabled
}

match_linux_wm [list frame .controls.inout.out.spacer]
Miller Puckette's avatar
Miller Puckette committed
675
676

pack .controls.inout.out.label .controls.inout.out.level \
677
678
679
680
681
682
683
684
685
686
687
688
689
690
    .controls.inout.out.clip .controls.inout.out.spacer -side top -pady 1

if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
	match_linux_wm [list ttk::button .controls.dio -text "\nIO Errors\n" \
		-command { if {![info exists show_console] || $show_console == 0} \
		{ menu_toggle_console; }; \
		pd [concat pd audiostatus \;]} \
		-width 8 -style IOErrorOff.TButton]
} else {
	button .controls.dio -text "DIO\nerrors" \
		-command { if {![info exists show_console] || $show_console == 0} \ 
		{ .controls.switches.console invoke; }; \
		pd [concat pd audiostatus \;]}
}
Miller Puckette's avatar
Miller Puckette committed
691

692
693
#match_linux_wm [list button .controls.clr_console -text "Clear Console" \
#	-command [concat menu_clear_console]]
Miller Puckette's avatar
Miller Puckette committed
694
695
696

pack .controls.inout.in .controls.inout.out -side left -padx 6
pack .controls.inout -side left -padx 14
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
697
698
699
pack .controls.switches -side right
pack .controls.dio -side right -padx 20

700
701
702
#if {[info exists show_console] && $show_console == 1} {
#	pack .controls.clr_console -pady 30
#}
Miller Puckette's avatar
Miller Puckette committed
703

704
705
toplevel .printout
wm title .printout "Console"
706
# initial location of the console window (+x+y)
707
wm geometry .printout +10+170
708
# wm minsize .printout 460 194
709
wm protocol .printout WM_DELETE_WINDOW { .controls.switches.console invoke }
710
711
match_linux_wm [list frame .printout.frame]
text .printout.frame.text -relief sunken -bd 1 -font console_font \
712
    -yscrollcommand ".printout.frame.scroll set"  -width 70 -height 24 \
713
	-highlightthickness 0 -takefocus 0 -fg gray20 -state disabled
714
715
716
717
718
719
720
721
722
723
#.printout.frame.text tag configure sel -background $linux_wm_hlcolor

# .printout.frame.text insert end "\n\n\n\n\n\n\n\n\n\n"
match_linux_wm [list scrollbar .printout.frame.scroll -command ".printout.frame.text yview"]
match_linux_wm [list frame .printout.bar]
match_linux_wm [list button .printout.bar.clear -text "CLEAR" \
	-width 7 -command [concat menu_clear_console]]
match_linux_wm [list entry .printout.bar.entry \
	-textvariable send_textvariable]
bind .printout.bar.entry <KeyPress-Return> {
724
	pdtk_post "\nmessage-to-pd: $send_textvariable"
725
726
727
728
    pd [concat $send_textvariable \;]
}
#match_linux_wm [list button .printout.bar.x -text "x" \
#	-width 2 -command [concat .printout.bar.entry delete 0 end]]
729
match_linux_wm [list label .printout.bar.label -text "Send Message to Pd:"]
730
731
732

pack .printout.frame.scroll -side right -fill y
pack .printout.frame.text -side left -fill both -expand 1
733
pack .printout.bar -side bottom -fill x -expand 0
734
735
736
pack .printout.frame -fill both -expand 1
pack .printout.bar.clear -side left -padx 3 -pady 3
#pack .printout.bar.x -side right -padx 3 -pady 3
737
pack .printout.bar.entry -side right -fill both -expand 1 -padx 5 -pady 3
738
pack .printout.bar.label -side right -padx 3 -pady 3
Miller Puckette's avatar
Miller Puckette committed
739

740
741
742
# the console is open by default
#.controls.switches.console select
# in the case console should be turned off by default
743
744
745
746
wm withdraw .printout
#wm geometry .printout 1x1+0+0
#wm overrideredirect .printout 1
#wm transient .printout
747

748
749
bind .printout.frame.text <Button> {pdtk_update_root_edit_menu 0}
bind .printout.frame.text <<Selection>> {pdtk_update_root_edit_menu 1}
750
bind .printout <Control-Next> {menu_raisenextwindow}	
751
bind .printout <Control-w> { .controls.switches.console invoke }
752
753

proc pdtk_update_root_edit_menu {value} {
754
	#pdtk_post "update_root_edit_menu $value\n"
755
	if {$value} {
756
		set range [.printout.frame.text tag ranges sel]
757
758
		#pdtk_post "[lindex $range 0] -- [lindex $range 1]\n"
		if {[lindex $range 0] != [lindex $range 1]} {
759
			#.mbar.edit entryconfigure "Cut" -state normal
760
761
762
763
			.mbar.edit entryconfigure "Copy" -state normal
		}
	} else {
		#pdtk_post off
764
		#.mbar.edit entryconfigure "Cut" -state disabled
765
766
767
768
		.mbar.edit entryconfigure "Copy" -state disabled
	}
}

Miller Puckette's avatar
Miller Puckette committed
769
proc pdtk_post {stuff} {
770
771
772
773
	.printout.frame.text configure -state normal
    .printout.frame.text insert end $stuff
    .printout.frame.text yview end-2char
	.printout.frame.text configure -state disabled
Miller Puckette's avatar
Miller Puckette committed
774
775
776
}

proc pdtk_standardkeybindings {id} {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
777
778
779
780
781
782
783
784
785
786
787
    global pd_nt ctrl_key
    bind $id <$ctrl_key-Key> {pdtk_canvas_ctrlkey %W %K 0}
    bind $id <$ctrl_key-Shift-Key> {pdtk_canvas_ctrlkey %W %K 1}
}

proc pdtk_panelkeybindings {id panelname} {
    global pd_nt ctrl_key
    pdtk_standardkeybindings $id
    bind $id <KeyPress-Escape> [format "%s_cancel %s" $panelname $id]
    bind $id <KeyPress-Return> [format "%s_ok %s" $panelname $id]
    bind $id <$ctrl_key-Key-w> [format "%s_cancel %s" $panelname $id]
Miller Puckette's avatar
Miller Puckette committed
788
789
790
}

pdtk_standardkeybindings .
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
791
# hacks to add standard key bindings to the Pd window
792
793
bind . <$ctrl_key-Key-a> {.printout.frame.text tag add sel 1.0 end}
#bind . <$ctrl_key-Key-x> {tk_textCut .printout.frame.text; \
794
#	.mbar.edit entryconfigure "Paste" -state normal}
795
bind . <$ctrl_key-Key-c> {tk_textCopy .printout.frame.text}
796
bind .printout <$ctrl_key-Key-c> {tk_textCopy .printout.frame.text}
797
#	.mbar.edit entryconfigure "Paste" -state normal}
798
#bind . <$ctrl_key-Key-v> {tk_textPaste .printout.frame.text}
799
bind . <$ctrl_key-Key-w> {menu_quit}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
800
801
802
803
804
# kludge to add window control bindings to the Pd Window
if {$pd_nt == 2} {
	bind . <Mod1-quoteleft>  {menu_raisenextwindow}
} else {
	bind . <Control-Next>    {menu_raisenextwindow}
805
	#bind . <Control-Prior>   {menu_raisepreviouswindow} ;# needs Tcl/Tk 8.5
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
806
}
Miller Puckette's avatar
Miller Puckette committed
807

808
809
810
811
812
813
814
815
# pass key presses inside main window to patch windows
proc pdtk_capture_root_window_keys {state key iso shift} {
	global menu_windowlist

	set first_patch_window_name [lindex $menu_windowlist 0 1]
	# pdtk_post "$first_patch_window_name\n"

	if { [string length $first_patch_window_name] > 0 } {
816
		pdtk_canvas_sendkey $first_patch_window_name.c $state $key $iso $shift 0
817
818
819
820
821
822
823
824
825
	}
}

bind . <Key> {pdtk_capture_root_window_keys 1 %K %A 0}
bind . <Shift-Key> {pdtk_capture_root_window_keys 1 %K %A 1}
bind . <KeyRelease> {pdtk_capture_root_window_keys 0 %K %A 0}
bind . <Control-Key> {pdtk_canvas_ctrlkey %W %K 0}
bind . <Control-Shift-Key> {pdtk_canvas_ctrlkey %W %K 1}

826
827
828
829
830
bind .printout <Key> {pdtk_capture_root_window_keys 1 %K %A 0}
bind .printout <Shift-Key> {pdtk_capture_root_window_keys 1 %K %A 1}
bind .printout <KeyRelease> {pdtk_capture_root_window_keys 0 %K %A 0}
bind .printout <Control-Key> {pdtk_canvas_ctrlkey %W %K 0}
bind .printout <Control-Shift-Key> {pdtk_canvas_ctrlkey %W %K 1}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
831

832
wm title . "Pure-Data L2Ork"
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
833
# initial location of Pd window (+x+y)
834
wm geometry . +10+35
835
836
837
838
catch {
	set appicon [image create photo -format gif -file "$pd_guidir/pd-48x48.gif"]
	wm iconphoto . -default $appicon
}
839
840
. configure -menu .mbar -width 200 -height 150
if { [info tclversion] >= 8.5 && $pd_nt == 0 } { wm resizable . 0 0 }
Miller Puckette's avatar
Miller Puckette committed
841
842
# Intercept closing the main pd window: MP 20060413:
wm protocol . WM_DELETE_WINDOW menu_quit
843
focus .
Miller Puckette's avatar
Miller Puckette committed
844

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
845

Miller Puckette's avatar
Miller Puckette committed
846
847
848
############### set up global variables ################################

set untitled_number 1
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
849
850
851
852
853
if {$pd_nt == 2} {
    set untitled_directory $::env(HOME)
} else {
    set untitled_directory [pwd]
}
Miller Puckette's avatar
Miller Puckette committed
854
855
set pd_opendir $untitled_directory
set pd_savedir $untitled_directory
856
857
858
#set pd_undoaction no
#set pd_redoaction no
#set pd_undocanvas no
Miller Puckette's avatar
Miller Puckette committed
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895

################ utility functions #########################

# enquote a string to send it to a tcl function
proc pdtk_enquote {x} {
    set foo [string map {"," "" ";" "" \" ""} $x]
    set foo2 [string map {" " "\\ "} $foo]
    concat $foo2
}

#enquote a string to send it to Pd.  Blow off semi and comma; alias spaces
#we also blow off "{", "}", "\" because they'll just cause bad trouble later.
proc pdtk_unspace {x} {
    set y [string map {" " "_" ";" "" "," "" "{" "" "}" "" "\\" ""} $x]
    if {$y == ""} {set y "empty"}
    concat $y
}

#enquote a string for preferences (command strings etc.)
proc pdtk_encodedialog {x} {
    concat +[string map {" " "+_" "$" "+d" ";" "+s" "," "+c" "+" "++"} $x]
}

proc pdtk_debug {x} {
    tk_messageBox -message $x -type ok
}

proc pdtk_watchdog {} {
    pd [concat pd watchdog \;]
    after 2000 {pdtk_watchdog}
}

proc pdtk_ping {} {
    pd [concat pd ping \;]
}

##### routine to ask user if OK and, if so, send a message on to Pd ######
Miller Puckette's avatar
Miller Puckette committed
896
proc pdtk_check {canvas x message default} {
Miller Puckette's avatar
Miller Puckette committed
897
    global pd_nt
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
898
	raise $canvas
Miller Puckette's avatar
Miller Puckette committed
899
900
901
902
903
904
    if {$pd_nt == 1} {
        set answer [tk_messageBox -message $x -type yesno -default $default \
            -icon question]
    } else {
        set answer [tk_messageBox -message $x -type yesno -default $default \
            -parent $canvas -icon question]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
905
    }
906
907
908
    if {! [string compare $answer yes]}  {
		pd $message
		if {$canvas eq "."} {
909
			focus $canvas
910
911
912
913
		} else {
			menu_close $canvas
		}
	}
Miller Puckette's avatar
Miller Puckette committed
914
915
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
916
917
918
919
920
##### ask user Save? Discard? Cancel?, and if so, send a message on to Pd ######
proc pdtk_canvas_menuclose {window reply} {
	global pd_nt
	raise $window
	set filename [wm title $window]
921
	set message [format {Do you wish to save the changes you made in "%s"?} $filename]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
922
923
924
	set answer [tk_messageBox -message $message -type yesnocancel -default "yes" \
					-parent $window -icon question]
	switch -- $answer {
925
		yes {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
926
			pd [concat $window menusave \;]
927
928
929
930
931
932
			#when quitting the application sometimes the save menu fails to show up
			#after 250 pd $reply
			#pd $reply
		}
		no {
			pd [concat $window dirty 0 \;]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
933
934
935
936
937
938
			pd $reply
		}
		cancel {}
	}
}

Miller Puckette's avatar
Miller Puckette committed
939
940
941
set menu_windowlist {} 

proc pdtk_fixwindowmenu {} {
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
    global menu_windowlist pd_nt k12_mode
	if { $k12_mode == 0 } {
		.mbar.windows delete 0 end
		if {$pd_nt == 2} {
			.mbar.windows add command -label {Minimize} -command {menu_minimize .} \
				-accelerator [accel_munge "Ctrl+m"]
			.mbar.windows add command -label {Zoom} -command {menu_zoom .}
		} else {
			.mbar.windows add command -label "Next Window" -command {menu_raisenextwindow} \
				-accelerator "Ctrl+PageDown"
			#.mbar.windows add command -label "Previous Window" -command {menu_raisepreviouswindow} \
			#	-accelerator "Ctrl+PageUp"
		}
		.mbar.windows add separator
		.mbar.windows add command -label {parent window} -state disabled
		.mbar.windows add command -label {Pd & Console} -command menu_raise_console \
			-accelerator [accel_munge "Ctrl+;"] -state disabled
		.mbar.windows add separator
		foreach i $menu_windowlist {
		    .mbar.windows add command -label [lindex $i 0] \
		        -command [concat menu_domenuwindow [lindex $i 1]]
		    menu_fixwindowmenu [lindex $i 1]
		}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
965
	}
Miller Puckette's avatar
Miller Puckette committed
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
}

####### Odd little function to make better Mac accelerators #####

proc accel_munge {acc} {
    global pd_nt

    if {$pd_nt == 2} {
        if [string is upper [string index $acc end]] {
            return [format "%s%s" "Shift+" \
                        [string toupper [string map {Ctrl Meta} $acc] end]]
        } else {
            return [string toupper [string map {Ctrl Meta} $acc] end]
        }
    } else {
        return $acc
    }
}



###############  the "New" menu command  ########################
proc menu_new {} {
    global untitled_number
    global untitled_directory
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
991
992
993
    if { ! [file isdirectory $untitled_directory]} {set untitled_directory $::env(HOME)}
    pd [concat pd filename Untitled-$untitled_number \
			[pdtk_enquote $untitled_directory] \;]
Miller Puckette's avatar
Miller Puckette committed
994
995
996
997
998
999
1000
1001
1002
    pd {
        #N canvas;
        #X pop 1;
    }
    set untitled_number [expr $untitled_number + 1]
}

################## the "Open" menu command #########################

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
proc menu_open {} {
    global pd_opendir filetypes
    if { ! [file isdirectory $pd_opendir]} {set pd_opendir $::env(HOME)}
    set files [tk_getOpenFile -defaultextension .pd \
					  -multiple true \
                      -filetypes $filetypes -initialdir $pd_opendir]
    if {$files != ""} {
		foreach filename $files {
			open_file $filename
		}
	}
Miller Puckette's avatar
Miller Puckette committed
1014
1015
}

1016
1017
1018
1019
1020
1021
1022
proc pdtk_set_current_dir {path_and_filename} {
	global pd_opendir untitled_directory
	set directory [file dirname $path_and_filename]
	set pd_opendir $directory
	set untitled_directory $directory
}

Miller Puckette's avatar
Miller Puckette committed
1023
proc open_file {filename} {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1024
    global pd_opendir pd_guidir pd_nt
1025
	#puts stderr open_file
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
	set directory [file dirname $filename]
	set basename [file tail $filename]
    if {[regexp -nocase -- "\.(pat|mxb|help)$" $basename]} {
		puts stderr "converting $filename"
		if {$pd_nt == 0} { 
			# on GNU/Linux, cyclist is installed into /usr/bin usually
			set cyclist "/usr/bin/cyclist" 
		} else {
			set cyclist "$pd_guidir/bin/cyclist"
		}
		puts stderr "$cyclist '$filename'"
		# convert Max binary to text .pat
		set binport [open "| \"$cyclist\" \"$filename\""]
		set convertedtext [read $binport]
		if { ! [catch {close $binport} err]} {
			if {! [file writable $directory]} {	set directory "/tmp" }
			set basename "$basename.pat"
			set textpatfile [open "$directory/$basename" w]
			puts $textpatfile $convertedtext
			close $textpatfile
			puts stderr "converted Max binary to text format: $directory/$basename"
		}
	}
    if {[regexp -nocase -- "\.(pd|pat|mxt)$" $basename]} {
Miller Puckette's avatar
Miller Puckette committed
1050
        pd "pd open [pdtk_enquote $basename] [pdtk_enquote $directory] ;"
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1051
        set pd_opendir $directory
Miller Puckette's avatar
Miller Puckette committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
    }
}

catch {
    package require tkdnd
    dnd bindtarget . text/uri-list <Drop> {
        foreach file %D {open_file $file}
    }
}

################## the "Message" menu command #########################
proc menu_send {} {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1064
    global pd_nt ctrl_key
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
    if { [winfo exists .sendpanel.entry] } {
        raise .sendpanel
    } else {
		toplevel .sendpanel
		wm title .sendpanel {Send Message to Pd}
		wm resizable .sendpanel 0 0
		match_linux_wm [list .sendpanel configure]
		pdtk_standardkeybindings .sendpanel
		match_linux_wm [list entry .sendpanel.entry \
			-textvariable send_textvariable]
		pack .sendpanel.entry -side bottom -fill both -ipadx 100 -padx 3 -pady 5
		if { [info tclversion] < 8.5 } {
			.sendpanel.entry select from 0
			.sendpanel.entry select adjust end
		}
		bind .sendpanel <$ctrl_key-Key-w> {destroy .sendpanel}
		bind .sendpanel <KeyPress-Escape> {destroy .sendpanel}
		bind .sendpanel.entry <KeyPress-Return> {
1083
			pdtk_post "\nmessage-to-pd: $send_textvariable"
1084
1085
1086
1087
		    pd [concat $send_textvariable \;]
		}
		focus .sendpanel.entry
	}
Miller Puckette's avatar
Miller Puckette committed
1088
1089
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105

################## menu commands for Mac OS X #########################

proc menu_minimize {window} {
	if {$window eq ""} { #Pd Window
		wm iconify [winfo toplevel .printout]
	} else {
		wm iconify [winfo toplevel $window]
	}
}

proc menu_zoom {window} {
	wm state $window zoomed
}

proc menu_raisenextwindow {} {
1106
1107
1108
1109
1110
1111
1112
	set target [lindex [wm stackorder .] 0]
	raise $target
	if { [winfo exists $target.c] } {
		focus $target.c
	} else {
		focus $target
	}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1113
1114
1115
}

# lreverse came along in Tcl 8.5
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
#proc menu_raisepreviouswindow {} {
#	set last [lindex [wm stackorder .] end]
#	set all [wm stackorder .]
#	foreach i $all {
#		if { $i != $last } { 
#			raise [lindex $i]
#			set target $i
#		} else {
#			if { [winfo exists $target.c] } {
#				focus $target.c
#			} else {
#				focus $target
#			}
#		}
#	}
#}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1132
1133
1134
1135
1136
1137

################## menu commands for console #########################

proc menu_raise_console {} {
	set pd_window .
	set top_window [lindex [wm stackorder $pd_window] end]
1138
	focus .
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1139
1140
	if {$pd_window eq $top_window} {
		lower $pd_window
1141
1142
1143
1144
		.controls.switches.console instate {selected} {
			lower .printout
		}
		#catch {lower .printout}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1145
1146
1147
	} else {
		wm deiconify $pd_window
		raise $pd_window
1148
1149
1150
1151
1152
1153
1154
1155
1156
		.controls.switches.console instate {selected} {
			wm deiconify .printout
			wm manage .printout
			raise .printout
			#focus .printout
		}
		#catch {wm deiconify .printout}
		#catch {wm manage .prinout}
		#raise .printout
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1157
1158
1159
	}
}

1160
proc menu_toggle_console {} { .controls.switches.console invoke }
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1161

1162
proc menu_clear_console {} {.printout.frame.text configure -state normal; .printout.frame.text delete 0.0 end; .printout.frame.text configure -state disabled}
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1163

Miller Puckette's avatar
Miller Puckette committed
1164
1165
1166
1167
1168
1169
1170
1171
################## the "Quit" menu command #########################
proc menu_really_quit {} {pd {pd quit;}}

proc menu_quit {} {pd {pd verifyquit;}}

######### the "audio" menu command  ###############
proc menu_audio {flag} {pd [concat pd dsp $flag \;]}

Miller Puckette's avatar
Miller Puckette committed
1172
1173
1174
######### the "reselect" menu command ################
proc menu_reselect {name} {pd [concat $name reselect \;]}

Miller Puckette's avatar
Miller Puckette committed
1175
1176
1177
1178
1179
1180
1181
1182
1183
######### the "documentation" menu command  ###############

set doc_number 1

# open text docs in a Pd window
proc menu_opentext {filename} {
    global doc_number
    global pd_guidir
    global pd_myversion
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1184
	global ctrl_key
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
    if { [winfo exists .about.text] } {
        raise .about
    } else {
		destroy .about
		toplevel .about
		wm title .about "About Pd"
		wm geometry .about 550x480
		match_linux_wm [list text .about.text -relief sunken -bd 1 -font text_font \
		    -yscrollcommand ".about.scroll set" -highlightthickness 0 -takefocus 0]
		match_linux_wm [list scrollbar .about.scroll -command ".about.text yview"]
		pack .about.scroll -side right -fill y
		pack .about.text -side left -fill both -expand 1
		bind .about <$ctrl_key-Key-w> [concat destroy .about set doc_number [expr $doc_number - 1]]
		
		set f [open $filename]
		while {![eof $f]} {
		    set bigstring [read $f 1000]
		    regsub -all PD_BASEDIR $bigstring $pd_guidir bigstring2
		    regsub -all PD_VERSION $bigstring2 $pd_myversion bigstring3
		    .about.text insert end $bigstring3
		}
		close $f
	}
Miller Puckette's avatar
Miller Puckette committed
1208
1209
1210
1211
1212
1213
1214
}

# open HTML docs from the menu using the OS-default HTML viewer
proc menu_openhtml {filename} {
    global pd_nt         

    if {$pd_nt == 0} {
1215
1216
        foreach candidate \
            { gnome-open xdg-open sensible-browser iceweasel firefox mozilla \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1217
1218
1219
                  galeon konqueror netscape lynx } {
                      set browser [lindex [auto_execok $candidate] 0]
                      if {[string length $browser]} {
1220
                          puts stderr [format "%s '%s'" $browser $filename]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1221
1222
1223
1224
                          exec -- sh -c [format "%s '%s'" $browser $filename] &
                          break
                      }
                  }
Miller Puckette's avatar
Miller Puckette committed
1225
    } elseif {$pd_nt == 2} {
1226
        puts stderr [format "open '%s'" $filename]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1227
        exec sh -c [format "open '%s'" $filename]
Miller Puckette's avatar
Miller Puckette committed
1228
1229
    } else {
        exec rundll32 url.dll,FileProtocolHandler \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1230
            [format "%s" $filename] &
Miller Puckette's avatar
Miller Puckette committed
1231
1232
1233
    }
}

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
proc menu_openpdpedia {} {
	set top_window [lindex [wm stackorder .] end]
	set window_title [wm title $top_window]
	set helpfile [regsub -- {(.*)-help.*} $window_title {\1}]
	if {$helpfile eq $window_title} {
		menu_openhtml "http://wiki.puredata.info/"
	} else {
		menu_openhtml "http://wiki.puredata.info/en/$helpfile"
	}
}

proc menu_doc_open {dir basename} {
Miller Puckette's avatar
Miller Puckette committed
1246
    global pd_guidir
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1247
1248
1249
1250
1251
1252
    
    if {[file pathtype $dir] eq "relative"} {
        set dirname "$pd_guidir/$dir"
    } else {
        set dirname $dir
    }
Miller Puckette's avatar
Miller Puckette committed
1253

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1254
1255
1256
    if {[file isdirectory [file join $dirname $basename]]} {
        menu_openhtml $dirname/$basename
    } elseif {[regexp -nocase -- ".*\.(txt|c)$" $basename]} {
Miller Puckette's avatar
Miller Puckette committed
1257
        menu_opentext $dirname/$basename
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1258
1259
    } elseif {[regexp -nocase -- ".*\.(htm|html|pdf)$" $basename]} {
        menu_openhtml $dirname/$basename
Miller Puckette's avatar
Miller Puckette committed
1260
    } else {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1261
1262
1263
        set fullpath [file normalize [file join $dirname $basename]]
        set dirname [file dirname $fullpath]
        set basename [file tail $fullpath]
Miller Puckette's avatar
Miller Puckette committed
1264
1265
1266
1267
1268
1269
1270
1271
1272
        pd [concat pd open [pdtk_enquote $basename] \
                [pdtk_enquote $dirname] \;]
    }
}

############# routine to add media, help, and apple menu items ###############

proc menu_addstd {mbar} {
    global pd_apilist pd_midiapilist pd_nt pd_tearoff
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1273
    #          the "Audio" menu
Miller Puckette's avatar
Miller Puckette committed
1274
1275
1276
1277
    $mbar.audio add command -label {audio ON} -accelerator [accel_munge "Ctrl+/"] \
        -command {menu_audio 1} 
    $mbar.audio add command -label {audio OFF} -accelerator [accel_munge "Ctrl+."] \
        -command {menu_audio 0} 
1278
	$mbar.audio add separator
Miller Puckette's avatar
Miller Puckette committed
1279
1280
1281
    for {set x 0} {$x<[llength $pd_apilist]} {incr x} {
        $mbar.audio add radiobutton -label [lindex [lindex $pd_apilist $x] 0] \
            -command {menu_audio 0} -variable pd_whichapi \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1282
1283
            -value [lindex [lindex $pd_apilist $x] 1]\
            -command {pd [concat pd audio-setapi $pd_whichapi \;]}
Miller Puckette's avatar
Miller Puckette committed
1284
    }
1285
	$mbar.audio add separator
Miller Puckette's avatar
Miller Puckette committed
1286
1287
1288
    for {set x 0} {$x<[llength $pd_midiapilist]} {incr x} {
        $mbar.audio add radiobutton -label [lindex [lindex $pd_midiapilist $x] 0] \
            -command {menu_midi 0} -variable pd_whichmidiapi \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1289
1290
1291
1292
            -value [lindex [lindex $pd_midiapilist $x] 1]\
            -command {pd [concat pd midi-setapi $pd_whichmidiapi \;]}
    }
    if {$pd_nt != 2} {
1293
		$mbar.audio add separator
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1294
1295
1296
1297
1298
        $mbar.audio add command -label {Audio settings...} \
            -command {pd pd audio-properties \;}
        $mbar.audio add command -label {MIDI settings...} \
            -command {pd pd midi-properties \;}
    }
1299
	$mbar.audio add separator    
Miller Puckette's avatar
Miller Puckette committed
1300
1301
1302
1303
1304
    $mbar.audio add command -label {Test Audio and MIDI} \
        -command {menu_doc_open doc/7.stuff/tools testtone.pd} 
    $mbar.audio add command -label {Load Meter} \
        -command {menu_doc_open doc/7.stuff/tools load-meter.pd} 

Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1305
1306
1307
1308
1309
1310
1311
1312
1313
    #       the MacOS X app menu

    # The menu on the main menubar named $whatever.apple while be treated
    # as a special menu on MacOS X.  Tcl/Tk assigns the $whatever.apple menu
    # to the app-specific menu in MacOS X that is named after the app,
    # so in our case, the Pd menu.  <hans@at.or.at>
    # See SPECIAL MENUS IN MENUBARS http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm
    if {$pd_nt == 2} {
        $mbar.apple add command -label "About Pd..." -command \
1314
            {menu_doc_open doc/1.manual 1.introduction.txt} 
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
        menu $mbar.apple.preferences -tearoff 0
        $mbar.apple add cascade -label "Preferences" -menu $mbar.apple.preferences
        $mbar.apple.preferences add command -label "Path..." \
            -command {pd pd start-path-dialog \;}
        $mbar.apple.preferences add command -label "Startup..." \
            -command {pd pd start-startup-dialog \;}
        $mbar.apple.preferences add command -label "Audio Settings..." \
            -command {pd pd audio-properties \;}
        $mbar.apple.preferences add command -label "MIDI settings..." \
            -command {pd pd midi-properties \;}
    }


    # the "Help" menu
Miller Puckette's avatar
Miller Puckette committed
1329
1330
    if {$pd_nt != 2} {
        $mbar.help add command -label {About Pd} \
1331
            -command {menu_doc_open doc/1.manual 1.introduction.txt} 
Miller Puckette's avatar
Miller Puckette committed
1332
    }
1333
    $mbar.help add command -label {Html} \
Miller Puckette's avatar
Miller Puckette committed
1334
        -command {menu_doc_open doc/1.manual index.htm} 
1335
    $mbar.help add command -label {Browser} \
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
        -accelerator [accel_munge "Ctrl+b"] \
        -command {::helpbrowser::open_helpbrowser}
    $mbar.help add separator
    $mbar.help add command -label {puredata.info} \
        -command {menu_openhtml http://puredata.info} 
    $mbar.help add command -label {Pdpedia} \
        -command {menu_openpdpedia} 
    $mbar.help add command -label {FAQ} \
        -command {menu_openhtml http://puredata.info/docs/faq} 
    $mbar.help add separator
    $mbar.help add command -label {mailing lists} \
        -command {menu_openhtml http://puredata.info/community/lists} 
    $mbar.help add command -label {forums} \
        -command {menu_openhtml http://puredata.hurleur.com/} 
    $mbar.help add command -label {IRC chat} \
        -command {menu_openhtml irc://irc.freenode.net/dataflow} 
    $mbar.help add separator
	$mbar.help add command -label {report bug} -command \
		{menu_openhtml {http://sourceforge.net/tracker/?func=add&group_id=55736&atid=478070}} 
Miller Puckette's avatar
Miller Puckette committed
1355
1356
1357
1358
1359
1360
}

#################### the "File" menu for the Pd window ##############

.mbar.file add command -label New -command {menu_new} \
    -accelerator [accel_munge "Ctrl+n"]
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1361
.mbar.file add command -label Open -command {menu_open} \
Miller Puckette's avatar
Miller Puckette committed
1362
1363
    -accelerator [accel_munge "Ctrl+o"]
.mbar.file add  separator
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1364
1365
1366
1367
1368
1369
1370
.mbar.file add command -label Close -accelerator [accel_munge "Ctrl+w"] \
	-state disabled
.mbar.file add command -label Save -accelerator [accel_munge "Ctrl+s"] \
	-state disabled
.mbar.file add command -label "Save as..." -accelerator [accel_munge "Ctrl+S"] \
	-state disabled
.mbar.file add  separator
Miller Puckette's avatar
Miller Puckette committed
1371
if {$pd_nt != 2} {
Hans-Christoph Steiner's avatar
Hans-Christoph Steiner committed
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
	.mbar.file add command -label "Message..." -command {menu_send} \
		-accelerator [accel_munge "Ctrl+m"]
	# On MacOS X, follow the standard Human Interface Guidelines
	# i.e. the Preferences menu under "Pd"
	.mbar.file add  separator
    .mbar.file add command -label Path... \
        -command {pd pd start-path-dialog \;}
    .mbar.f