forked from elbrujohalcon/hPage
/
FreeTextWindow.hs
1075 lines (977 loc) · 50 KB
/
FreeTextWindow.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
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
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE GeneralizedNewtypeDeriving,
MultiParamTypeClasses,
FlexibleInstances,
FlexibleContexts,
FunctionalDependencies,
UndecidableInstances #-}
module HPage.GUI.FreeTextWindow ( gui ) where
import Prelude hiding (catch)
import Control.Exception
import Control.Concurrent.Process
import Control.Concurrent.MVar
import System.FilePath
import System.Directory
import System.IO.Error hiding (try, catch)
import Data.List
import Data.Bits
import Data.Char (toLower)
import Data.Version
import Distribution.Package
import Control.Monad.Error
import Control.Monad.Loops
import Graphics.UI.WX
import Graphics.UI.WXCore hiding (kill, Process)
import qualified HPage.Control as HP
import qualified HPage.Server as HPS
import HPage.GUI.Dialogs
import HPage.GUI.IDs
import HPage.GUI.Constants
import HPage.Utils.Log
import Paths_hpage -- cabal locations of data files
imageFile :: FilePath -> IO FilePath
imageFile fp = do
path <- getDataFileName $ "res/images/" ++ fp
real <- doesFileExist path
if real then return path
else do
errorIO ("file not found", path)
fail (path ++ " does not exist")
helpFile :: IO FilePath
helpFile = getDataFileName "res/help/helpPage.hs"
data GUIBottom = GUIBtm { bottomDesc :: String,
bottomSource :: String }
data GUIResults = GUIRes { resButton :: Button (),
resLabel :: StaticText (),
resValue :: TextCtrl (),
res4Dots :: StaticText (),
resType :: TextCtrl (),
resErrors :: Var [GUIBottom] }
data GUIContext = GUICtx { guiWin :: Frame (),
guiPages :: SingleListBox (),
guiModules :: (Var Int, ListCtrl ()),
guiCode :: TextCtrl (),
guiResults :: GUIResults,
guiStatus :: StatusField,
guiTimer :: TimerEx (),
guiCharTimer :: TimerEx (),
guiSearch :: FindReplaceData (),
guiChrVar :: MVar (Maybe String),
guiChrFiller :: MVar (Handle String),
guiValFiller :: MVar (Handle (String, IO ()))}
gui :: IO ()
gui =
do
-- Server context
model <- HPS.start
win <- frame [text := "\955Page",
visible := False]
imageFile "icon/hpage.tif" >>= topLevelWindowSetIconFromFile win
set win [on closing := HPS.stop model >> propagateEvent]
-- Containers
ntbkL <- notebook win []
pnlPs <- panel ntbkL []
pnlMs <- panel ntbkL []
-- Text page...
-- txtCode <- styledTextCtrl win []
txtCode <- textCtrl win [font := fontFixed, text := ""]
-- Document Selector
lstPages <- singleListBox pnlPs [style := wxLB_NEEDED_SB, outerSize := sz 400 600]
-- Modules Lists
imageFiles <- mapM imageFile ["m_imported.ico", "m_interpreted.ico", "m_compiled.ico", "m_package.ico"]
imagePaths <- mapM getAbsoluteFilePath imageFiles
images <- imageListFromFiles (sz 16 16) imagePaths
varModsSel <- varCreate $ -1
lstModules <- listCtrlEx pnlMs (wxLC_REPORT + wxLC_ALIGN_LEFT + wxLC_NO_HEADER + wxLC_SINGLE_SEL)
[columns := [("Module", AlignLeft, 200),
("Origin", AlignLeft, 1)]]
listCtrlSetImageList lstModules images wxIMAGE_LIST_SMALL
-- Results panel
pnlRes <- panel win []
txtValue <- textEntry pnlRes [style := wxTE_READONLY]
varErrors <- varCreate []
txtType <- textEntry pnlRes [style := wxTE_READONLY]
btnInterpret <- button pnlRes [text := "Interpret"]
lblInterpret <- staticText pnlRes [text := "Value:"]
lbl4Dots <- staticText pnlRes [text := " :: "]
set pnlRes [layout := fill $
row 5 [widget btnInterpret,
centre $ widget lblInterpret,
fill $ widget txtValue,
centre $ widget lbl4Dots,
fill $ widget txtType]]
-- Status bar...
status <- statusField [text := "hello... this is \955Page! type in your instructions :)"]
set win [statusBar := [status]]
-- Timers ...
refreshTimer <- timer win []
charTimer <- timer win []
-- Search ...
search <- findReplaceDataCreate wxFR_DOWN
chv <- newEmptyMVar
chfv <- newEmptyMVar
vfv <- newEmptyMVar
let guiRes = GUIRes btnInterpret lblInterpret txtValue lbl4Dots txtType varErrors
let guiCtx = GUICtx win lstPages (varModsSel, lstModules) txtCode guiRes status refreshTimer charTimer search chv chfv vfv
let onCmd name acc = traceIO ("onCmd", name) >> acc model guiCtx
-- Helper processes
chf <- spawn $ charFiller guiCtx
putMVar chfv chf
vf <- spawn $ valueFiller guiCtx
putMVar vfv vf
-- Events
timerOnCommand refreshTimer $ refreshExpr model guiCtx
timerOnCommand charTimer $ do
wasEmpty <- tryPutMVar chv Nothing
if wasEmpty
then do
newchf <- spawn $ charFiller guiCtx
swapMVar chfv newchf >>= kill
else return ()
set btnInterpret [on command := onCmd "interpret" interpret]
set lstPages [on select := onCmd "pageChange" pageChange]
set txtCode [on keyboard := onCmd "key" . keyEvent,
on mouse := \e -> case e of
MouseLeftUp _ _ -> onCmd "mouseEvent" restartTimer >> propagateEvent
MouseLeftDClick _ _ -> onCmd "mouseEvent" restartTimer >> propagateEvent
MouseRightDown _ _ -> onCmd "textContextMenu" textContextMenu
_ -> propagateEvent]
set txtValue [on mouse := \e -> case e of
MouseRightDown _ _ -> onCmd "valueContextMenu" valueContextMenu
_ -> propagateEvent]
set txtType [on mouse := \e -> case e of
MouseRightDown _ _ -> onCmd "typeContextMenu" typeContextMenu
_ -> propagateEvent]
set lstModules [on listEvent := \e -> case e of
ListItemSelected idx -> varSet varModsSel idx
ListItemRightClick idx -> varSet varModsSel idx >> onCmd "moduleContextMenu" moduleContextMenu
_ -> propagateEvent]
-- Menu bar...
mnuPage <- menuPane [text := "Page"]
menuAppend mnuPage wxId_NEW "&New\tCtrl-n" "New Page" False
menuAppend mnuPage wxId_CLOSE "&Close\tCtrl-w" "Close Page" False
menuAppend mnuPage wxId_CLOSE_ALL "&Close All\tCtrl-Shift-w" "Close All Pages" False
menuAppendSeparator mnuPage
menuAppend mnuPage wxId_OPEN "&Open...\tCtrl-o" "Open Page" False
menuAppend mnuPage wxId_SAVE "&Save\tCtrl-s" "Save Page" False
menuAppend mnuPage wxId_SAVEAS "&Save as...\tCtrl-Shift-s" "Save Page as" False
menuAppendSeparator mnuPage
menuQuit mnuPage [on command := wxcAppExit]
mnuEdit <- menuPane [text := "Edit"]
menuAppend mnuEdit wxId_UNDO "&Undo\tCtrl-z" "Undo" False
menuAppend mnuEdit wxId_REDO "&Redo\tCtrl-Shift-z" "Redo" False
menuAppendSeparator mnuEdit
menuAppend mnuEdit wxId_CUT "C&ut\tCtrl-x" "Cut" False
menuAppend mnuEdit wxId_COPY "&Copy\tCtrl-c" "Copy" False
menuAppend mnuEdit wxId_PASTE "&Paste\tCtrl-v" "Paste" False
menuAppendSeparator mnuEdit
menuAppend mnuEdit wxId_FIND "&Find...\tCtrl-f" "Find" False
menuAppend mnuEdit wxId_FORWARD "Find &Next\tCtrl-g" "Find Next" False
menuAppend mnuEdit wxId_BACKWARD "Find &Previous\tCtrl-Shift-g" "Find Previous" False
menuAppend mnuEdit wxId_REPLACE "&Replace...\tCtrl-Shift-r" "Replace" False
menuAppendSeparator mnuEdit
menuAppend mnuEdit wxId_PREFERENCES "&Preferences...\tCtrl-," "Preferences" False
mnuHask <- menuPane [text := "Haskell"]
menuAppend mnuHask wxId_HASK_LOAD_PKG "Load &package...\tCtrl-Alt-l" "Load Cabal Package" False
menuAppendSeparator mnuHask
menuAppend mnuHask wxId_HASK_LOAD "&Load modules...\tCtrl-l" "Load Modules" False
menuAppend mnuHask wxId_HASK_LOADNAME "Load modules by &name...\tCtrl-Shift-l" "Load Modules by Name" False
menuAppend mnuHask wxId_HASK_ADD "Import modules...\tCtrl-Shift-i" "Import Packaged Modules by Name" False
menuAppend mnuHask wxId_HASK_RELOAD "&Reload\tCtrl-r" "Reload Modules" False
menuAppendSeparator mnuHask
menuAppend mnuHask wxId_HASK_INTERPRET "&Interpret\tCtrl-i" "Interpret the Current Expression" False
menuAppend mnuHask wxId_HASK_NAVIGATE "Search on Ha&yoo!\tCtrl-y" "Search the Current Selection on Hayoo!" False
mnuHelp <- menuHelp []
menuAppend mnuHelp wxId_HELP "&Help page\tCtrl-h" "Open the Help Page" False
menuAbout mnuHelp [on command := infoDialog win "About \955Page" "Author: Fernando Brujo Benavides\nWebsite: http://haskell.hpage.com"]
set win [menuBar := [mnuPage, mnuEdit, mnuHask, mnuHelp]]
evtHandlerOnMenuCommand win wxId_NEW $ onCmd "runHP' addPage" $ runHP' HP.addPage
evtHandlerOnMenuCommand win wxId_CLOSE $ onCmd "runHP' closePage" $ runHP' HP.closePage
evtHandlerOnMenuCommand win wxId_CLOSE_ALL $ onCmd "runHP' closeAllPages" $ runHP' HP.closeAllPages
evtHandlerOnMenuCommand win wxId_OPEN $ onCmd "openPage" openPage
evtHandlerOnMenuCommand win wxId_SAVE $ onCmd "savePage" savePage
evtHandlerOnMenuCommand win wxId_SAVEAS $ onCmd "savePageAs" savePageAs
evtHandlerOnMenuCommand win wxId_UNDO $ onCmd "runHP' undo" $ runHP' HP.undo
evtHandlerOnMenuCommand win wxId_REDO $ onCmd "runHP' redo" $ runHP' HP.redo
evtHandlerOnMenuCommand win wxId_CUT $ onCmd "cut" cut
evtHandlerOnMenuCommand win wxId_COPY $ onCmd "copy" copy
evtHandlerOnMenuCommand win wxId_PASTE $ onCmd "paste" paste
evtHandlerOnMenuCommand win wxId_FIND $ onCmd "justFind" justFind
evtHandlerOnMenuCommand win wxId_FORWARD $ onCmd "findNext" justFindNext
evtHandlerOnMenuCommand win wxId_BACKWARD $ onCmd "findPrev" justFindPrev
evtHandlerOnMenuCommand win wxId_REPLACE $ onCmd "findReplace" findReplace
evtHandlerOnMenuCommand win wxId_HASK_LOAD_PKG $ onCmd "loadPackage" loadPackage
evtHandlerOnMenuCommand win wxId_HASK_LOAD $ onCmd "loadModules" loadModules
evtHandlerOnMenuCommand win wxId_HASK_ADD $ onCmd "importModules" importModules
evtHandlerOnMenuCommand win wxId_HASK_LOADNAME $ onCmd "loadModulesByName" loadModulesByName
evtHandlerOnMenuCommand win wxId_HASK_LOAD_FAST $ onCmd "loadModulesByNameFast" loadModulesByNameFast
evtHandlerOnMenuCommand win wxId_HASK_RELOAD $ onCmd "reloadModules" reloadModules
evtHandlerOnMenuCommand win wxId_PREFERENCES $ onCmd "preferences" configure
evtHandlerOnMenuCommand win wxId_HASK_INTERPRET $ onCmd "interpret" interpret
evtHandlerOnMenuCommand win wxId_HASK_NAVIGATE $ onCmd "hayoo" hayoo
evtHandlerOnMenuCommand win wxId_HASK_COPY $ onCmd "copyResult" copyResult
evtHandlerOnMenuCommand win wxId_HASK_COPY_TYPE $ onCmd "copyType" copyType
evtHandlerOnMenuCommand win wxId_HASK_EXPLAIN $ onCmd "explain" explain
evtHandlerOnMenuCommand win wxId_HELP $ onCmd "help" openHelpPage
-- Tool bar...
tbMain <- toolBarEx win True True []
mitLoadPkg <- menuFindItem mnuHask wxId_HASK_LOAD_PKG
mitNew <- menuFindItem mnuPage wxId_NEW
mitOpen <- menuFindItem mnuPage wxId_OPEN
mitSave <- menuFindItem mnuPage wxId_SAVE
mitCut <- menuFindItem mnuEdit wxId_CUT
mitCopy <- menuFindItem mnuEdit wxId_COPY
mitPaste <- menuFindItem mnuEdit wxId_PASTE
mitReload <- menuFindItem mnuHask wxId_HASK_RELOAD
loadPath <- imageFile "load.png"
newPath <- imageFile "new.png"
openPath <- imageFile "open.png"
savePath <- imageFile "save.png"
cutPath <- imageFile "cut.png"
copyPath <- imageFile "copy.png"
pastePath <- imageFile "paste.png"
reloadPath <- imageFile "reload.png"
toolMenu tbMain mitLoadPkg "Load Package" loadPath [tooltip := "Load Cabal Package"]
toolBarAddSeparator tbMain
toolMenu tbMain mitNew "New" newPath [tooltip := "New Page"]
toolMenu tbMain mitOpen "Open" openPath [tooltip := "Open Page"]
toolMenu tbMain mitSave "Save" savePath [tooltip := "Save Page"]
toolBarAddSeparator tbMain
toolMenu tbMain mitCut "Cut" cutPath [tooltip := "Cut"]
toolMenu tbMain mitCopy "Copy" copyPath [tooltip := "Copy"]
toolMenu tbMain mitPaste "Paste" pastePath [tooltip := "Paste"]
toolBarAddSeparator tbMain
toolMenu tbMain mitReload "Reload" reloadPath [tooltip := "Reload Modules"]
toolBarSetToolBitmapSize tbMain $ sz 32 32
-- Layout settings
let pagesTabL = tab "Pages" $ container pnlPs $ fill $ margin 5 $ widget lstPages
modsTabL = tab "Modules" $ container pnlMs $ fill $ margin 5 $ widget lstModules
leftL = tabs ntbkL [modsTabL, pagesTabL]
resultsL = hfill $ boxed "Expression" $ fill $ widget pnlRes
rightL = minsize (sz 485 100) $ fill $ widget txtCode
set win [layout := column 5 [fill $ row 10 [leftL, rightL], resultsL],
clientSize := sz 800 600]
-- test the server...
runTxtHPSelection "1" model HP.interpret
-- ...and RUN!
refreshPage model guiCtx
onCmd "start" openHelpPage
set win [visible := True]
set txtCode [font := fontFixed] -- again just to be sure
focusOn txtCode
-- PROCESSES -------------------------------------------------------------------
charFiller :: GUIContext -> Process String ()
charFiller GUICtx{guiResults = GUIRes{resValue = txtValue,
resErrors= varErrors},
guiChrVar = chv} =
forever $ do
t <- recv
liftIO $ do
txt <- catch (eval t) $ \(ErrorCall desc) ->
varUpdate varErrors (++ [GUIBtm desc t]) >>
return bottomChar
tryPutMVar chv $ Just txt
where eval t = t `seq` length t `seq` return t
valueFiller :: GUIContext -> Process (String, IO ()) ()
valueFiller guiCtx@GUICtx{guiResults = GUIRes{resButton = btnInterpret,
resErrors = varErrors,
resValue = txtValue}} =
forever $ do
liftDebugIO "Waiting for a new value to interpret"
(val, poc) <- recv
liftDebugIO "Value received in valueFiller"
liftDebugIO "Trying to evaluate the whole value first..."
liftIO $ do
set txtValue [text := ""]
res <- valueFill guiCtx val
if res == bottomChar
then do
debugIO "didn't work... going char by char..."
varSet varErrors []
valueFiller' guiCtx val
else do
debugIO "It worked!!"
textCtrlAppendText txtValue res
set btnInterpret [on command := poc,
text := "Interpret"]
set txtValue [enabled := True,
bgcolor := white]
valueFiller' :: GUIContext -> String -> IO ()
valueFiller' guiCtx@GUICtx{guiResults = GUIRes{resValue = txtValue,
resErrors = varErrors}} val =
do
h <- try (case val of
[] -> return []
(c:_) -> return [c])
case h of
Left (ErrorCall desc) ->
do
varUpdate varErrors (++ [GUIBtm desc val])
textCtrlAppendText txtValue bottomString
Right [] ->
return ()
Right t ->
do
valueFill guiCtx t >>= textCtrlAppendText txtValue
valueFiller' guiCtx $ tail val
valueFill :: GUIContext -> String -> IO String
valueFill GUICtx{guiResults = GUIRes{resErrors = varErrors},
guiCharTimer = charTimer,
guiChrVar = chv,
guiChrFiller = chfv} val =
do
debugIO "valueFill starting..."
tryTakeMVar chv --NOTE: empty the var
debugIO "timer starting..."
timerStart charTimer charTimeout True
debugIO "sending msg to charFiller..."
readMVar chfv >>= flip sendTo val
debugIO "waiting for value toAdd..."
toAdd <- readMVar chv --NOTE: Not using "take" to be sure that noone touches it
debugIO ("Ready to add...", toAdd)
case toAdd of
Just txt ->
do
isR <- timerIsRuning charTimer
if isR then timerStop charTimer else return ()
debugIO $ "returning " ++ txt
return txt
Nothing -> --NOTE: Means "Timed Out"
do
varUpdate varErrors (++ [GUIBtm "Timed Out" val])
debugIO $ "timed out"
return bottomChar
-- EVENT HANDLERS --------------------------------------------------------------
keyEvent :: EventKey -> HPS.ServerHandle -> GUIContext -> IO ()
keyEvent eventKey model guiCtx@GUICtx{guiCode = txtCode} =
do
case keyKey eventKey of
KeyTab ->
if isNoneDown (keyModifiers eventKey)
then
textCtrlWriteText txtCode "\t" >> restartTimer model guiCtx
else
return ()
_ ->
restartTimer model guiCtx
propagateEvent
refreshPage, savePageAs, savePage, openPage,
pageChange, copy, copyResult, copyType, cut, paste,
justFind, justFindNext, justFindPrev, findReplace,
textContextMenu, moduleContextMenu, valueContextMenu,
restartTimer, interpret, hayoo, explain,
loadPackage, loadModules, importModules, loadModulesByName, loadModulesByNameFast, reloadModules,
configure, openHelpPage :: HPS.ServerHandle -> GUIContext -> IO ()
moduleContextMenu model guiCtx@GUICtx{guiWin = win, guiModules = (varModsSel, lstModules)} =
do
pointWithinWindow <- windowGetMousePosition win
i <- varGet varModsSel
contextMenu <- menuPane []
case i of
(-1) ->
do
return ()
i ->
do
itm <- get lstModules $ item i
case itm of
[_, "Package"] ->
menuAppend contextMenu wxId_HASK_LOAD_FAST "&Load" "Load Module" False
[modname, _] ->
appendBrowseMenu contextMenu modname
other ->
menuAppend contextMenu idAny (show other) "Other" False
propagateEvent
menuPopup contextMenu pointWithinWindow win
objectDelete contextMenu
where appendBrowseMenu contextMenu mn =
do
browseMenu <- menuPane []
hpsRes <- tryIn model $ HP.getModuleExports mn
case hpsRes of
Left err ->
menuAppend browseMenu idAny err "Error" False
Right mes ->
flip mapM_ mes $ createMenuItem browseMenu
menuItem contextMenu [text := "To Clipboard",
on command := addToClipboard mn]
menuItem contextMenu [text := "Search on Hayoo!",
on command := hayooDialog win mn]
menuAppendSeparator contextMenu
menuAppendSub contextMenu wxId_HASK_BROWSE "&Browse" browseMenu ""
addToClipboard txt =
do
tdo <- textDataObjectCreate txt
cb <- clipboardCreate
opened <- clipboardOpen cb
if opened
then do
r <- clipboardSetData cb tdo
if r
then return ()
else errorDialog win "Error" "Clipboard operation failed"
clipboardClose cb
else
errorDialog win "Error" "Clipboard not ready"
createMenuItem m fn@HP.MEFun{HP.funName = fname} =
do
itemMenu <- createBasicMenuItem fname
menuAppendSub m wxId_HASK_MENUELEM (show fn) itemMenu ""
createMenuItem m HP.MEClass{HP.clsName = cn, HP.clsFuns = []} =
do
itemMenu <- createBasicMenuItem cn
menuAppendSub m wxId_HASK_MENUELEM ("class " ++ cn) itemMenu ""
createMenuItem m HP.MEClass{HP.clsName = cn, HP.clsFuns = cfs} =
do
subMenu <- createBasicMenuItem cn
menuAppendSeparator subMenu
flip mapM_ cfs $ createMenuItem subMenu
menuAppendSub m wxId_HASK_MENUELEM ("class " ++ cn) subMenu ""
createMenuItem m HP.MEData{HP.datName = dn, HP.datCtors = []} =
do
itemMenu <- createBasicMenuItem dn
menuAppendSub m wxId_HASK_MENUELEM ("data " ++ dn) itemMenu ""
createMenuItem m HP.MEData{HP.datName = dn, HP.datCtors = dcs} =
do
subMenu <- createBasicMenuItem dn
menuAppendSeparator subMenu
flip mapM_ dcs $ createMenuItem subMenu
menuAppendSub m wxId_HASK_MENUELEM ("data " ++ dn) subMenu ""
createBasicMenuItem name =
do
itemMenu <- menuPane []
menuItem itemMenu [text := "To Clipboard",
on command := addToClipboard name]
menuItem itemMenu [text := "Search on Hayoo!",
on command := hayooDialog win name]
return itemMenu
textContextMenu model guiCtx@GUICtx{guiWin = win, guiCode = txtCode} =
do
contextMenu <- menuPane []
sel <- textCtrlGetStringSelection txtCode
case sel of
"" ->
return ()
_ ->
do
menuAppend contextMenu wxId_CUT "C&ut\tCtrl-x" "Cut" False
menuAppend contextMenu wxId_COPY "&Copy\tCtrl-c" "Copy" False
menuAppend contextMenu wxId_PASTE "&Paste\tCtrl-v" "Paste" False
menuAppendSeparator contextMenu
menuAppend contextMenu wxId_HASK_NAVIGATE "Search on Ha&yoo!\tCtrl-y" "Search the Current Selection on Hayoo!" False
menuAppend contextMenu wxId_HASK_INTERPRET "&Interpret\tCtrl-i" "Interpret the Current Expression" False
propagateEvent
pointWithinWindow <- windowGetMousePosition win
menuPopup contextMenu pointWithinWindow win
objectDelete contextMenu
valueContextMenu model guiCtx@GUICtx{guiWin = win,
guiResults = GUIRes{resValue = txtValue}} =
do
contextMenu <- menuPane []
sel <- textCtrlGetStringSelection txtValue
case sel of
"" ->
return ()
_ ->
menuAppend contextMenu wxId_HASK_COPY "Copy" "Copy" False
if sel == bottomChar || sel == bottomString
then menuAppend contextMenu wxId_HASK_EXPLAIN "Explain" "Explain" False
else return ()
propagateEvent
pointWithinWindow <- windowGetMousePosition win
menuPopup contextMenu pointWithinWindow win
objectDelete contextMenu
typeContextMenu model guiCtx@GUICtx{guiWin = win,
guiResults = GUIRes{resType = txtType}} =
do
contextMenu <- menuPane []
sel <- textCtrlGetStringSelection txtType
case sel of
"" ->
do
propagateEvent
objectDelete contextMenu
_ ->
do
menuAppend contextMenu wxId_HASK_COPY_TYPE "Copy" "Copy" False
propagateEvent
pointWithinWindow <- windowGetMousePosition win
menuPopup contextMenu pointWithinWindow win
objectDelete contextMenu
pageChange model guiCtx@GUICtx{guiPages = lstPages} =
do
i <- get lstPages selection
case i of
(-1) -> return ()
_ -> runHP' (HP.setPageIndex i) model guiCtx
openPage model guiCtx@GUICtx{guiWin = win,
guiStatus = status} =
do
fileNames <- filesOpenDialog win True True "Open file..." [("Haskells",["*.hs"]),
("Any file",["*.*"])] "" ""
case fileNames of
[] ->
return ()
fs ->
do
set status [text := "opening..."]
flip mapM_ fs $ \f -> runHP' (HP.openPage f) model guiCtx
savePageAs model guiCtx@GUICtx{guiWin = win, guiStatus = status} =
do
fileName <- fileSaveDialog win True True "Save file..." [("Haskells",["*.hs"]),
("Any file",["*.*"])] "" ""
case fileName of
Nothing ->
return ()
Just f ->
do
set status [text := "saving..."]
runHP' (HP.savePageAs f) model guiCtx
savePage model guiCtx@GUICtx{guiWin = win} =
do
maybePath <- tryIn' model HP.getPagePath
case maybePath of
Left err ->
warningDialog win "Error" err
Right Nothing ->
savePageAs model guiCtx
Right _ ->
do
set (guiStatus guiCtx) [text := "saving..."]
runHP' HP.savePage model guiCtx
copy _model GUICtx{guiCode = txtCode} = textCtrlCopy txtCode
copyResult _model GUICtx{guiResults = GUIRes{resValue = txtValue}} = textCtrlCopy txtValue
copyType _model GUICtx{guiResults = GUIRes{resType = txtType}} = textCtrlCopy txtType
cut model guiCtx@GUICtx{guiCode = txtCode} = textCtrlCut txtCode >> refreshExpr model guiCtx
paste model guiCtx@GUICtx{guiCode = txtCode} = textCtrlPaste txtCode >> refreshExpr model guiCtx
justFind model guiCtx = openFindDialog model guiCtx "Find..." dialogDefaultStyle
justFindNext model guiCtx@GUICtx{guiSearch = search} =
do
curFlags <- findReplaceDataGetFlags search
findReplaceDataSetFlags search $ curFlags .|. wxFR_DOWN
findNextButton model guiCtx
justFindPrev model guiCtx@GUICtx{guiSearch = search} =
do
curFlags <- findReplaceDataGetFlags search
findReplaceDataSetFlags search $ curFlags .&. complement wxFR_DOWN
findNextButton model guiCtx
findReplace model guiCtx = openFindDialog model guiCtx "Find and Replace..." $ dialogDefaultStyle .|. wxFR_REPLACEDIALOG
reloadModules = runHP HP.reloadModules
loadPackage model guiCtx@GUICtx{guiWin = win} =
do
distExists <- doesDirectoryExist "dist"
let startDir = if distExists then "dist" else ""
res <- fileOpenDialog win True True "Select the setup-config file for your project..."
[("setup-config",["setup-config"])] startDir "setup-config"
case res of
Nothing ->
return ()
Just setupConfig ->
do
loadres <- tryIn' model $ do
lr <- HP.loadPackage setupConfig
HP.addPage
return lr
case loadres of
Left err ->
warningDialog win "Error" err
Right (Left err) ->
warningDialog win "Error" err
Right (Right pkg) ->
do
absPath <- canonicalizePath setupConfig
let dir = joinPath . reverse . drop 2 . reverse $ splitDirectories absPath
setCurrentDirectory dir
frameSetTitle win $ "\955Page - " ++ prettyShow pkg
refreshPage model guiCtx
where prettyShow PackageIdentifier{pkgName = PackageName pkgname,
pkgVersion = pkgvsn} = pkgname ++ "-" ++ showVersion pkgvsn
loadModules model guiCtx@GUICtx{guiWin = win, guiStatus = status} =
do
fileNames <- filesOpenDialog win True True "Load Module..." [("Haskell Modules",["*.hs"])] "" ""
case fileNames of
[] ->
return ()
fs ->
do
set status [text := "loading..."]
runHP (HP.loadModules fs) model guiCtx
loadModulesByName model guiCtx@GUICtx{guiWin = win, guiStatus = status} =
do
moduleNames <- textDialog win "Enter the module names, separated by spaces" "Load Modules..." ""
case moduleNames of
"" ->
return ()
mns ->
do
set status [text := "loading..."]
runHP (HP.loadModules $ words mns) model guiCtx
loadModulesByNameFast model guiCtx@GUICtx{guiWin = win, guiModules = (varModsSel, lstModules), guiStatus = status} =
do
i <- varGet varModsSel
case i of
(-1) -> return ()
i ->
do
mnText <- listCtrlGetItemText lstModules i
let mns = [mnText]
set status [text := "loading..."]
runHP (HP.loadModules mns) model guiCtx
importModules model guiCtx@GUICtx{guiWin = win, guiStatus = status} =
do
moduleNames <- textDialog win "Enter the module names, separated by spaces" "Import Packaged Modules..." ""
case moduleNames of
"" ->
return ()
mns ->
do
set status [text := "loading..."]
runHP (HP.importModules $ words mns) model guiCtx
configure model guiCtx@GUICtx{guiWin = win, guiStatus = status} =
do
hpsRes <- tryIn model $ do
les <- HP.getLanguageExtensions
sds <- HP.getSourceDirs
gos <- HP.getGhcOpts
case les of
Left e -> return $ Left e
Right l -> return $ Right (l, sds, gos)
case hpsRes of
Left err ->
warningDialog win "Error" err
Right (les, sds, gos) ->
do
res <- preferencesDialog win "Preferences" $ Prefs les sds gos
case res of
Nothing ->
return ()
Just newps ->
do
set status [text := "setting..."]
runHP (do
HP.setLanguageExtensions $ languageExtensions newps
HP.setSourceDirs $ sourceDirs newps
case ghcOptions newps of
"" -> return $ Right ()
newopts -> HP.setGhcOpts newopts
) model guiCtx
openHelpPage model guiCtx@GUICtx{guiCode = txtCode} =
do
f <- helpFile
txt <- readFile f
set txtCode [font := fontFixed,
text := txt]
-- Refresh the current expression box
refreshExpr model guiCtx
refreshPage model guiCtx@GUICtx{guiWin = win,
guiPages = lstPages,
guiModules = (varModsSel, lstModules),
guiCode = txtCode,
guiStatus = status} =
do
res <- tryIn' model $ do
pc <- HP.getPageCount
pages <- mapM HP.getPageNthDesc [0..pc-1]
ind <- HP.getPageIndex
txt <- HP.getPageText
lmsRes <- HP.getLoadedModules
ims <- HP.getImportedModules
pms <- HP.getPackageModules
let lms = case lmsRes of
Left _ -> []
Right x -> x
return (pms, ims, lms, pages, ind, txt)
case res of
Left err ->
warningDialog win "Error" err
Right (pms, ims, ms, ps, i, t) ->
do
-- Refresh the pages list
itemsDelete lstPages
(flip mapM) ps $ \pd ->
let prefix = if HP.pIsModified pd
then "*"
else ""
name = case HP.pPath pd of
Nothing -> "new page"
Just fn -> takeFileName $ dropExtension fn
in itemAppend lstPages $ prefix ++ name
set lstPages [selection := i]
-- Refresh the modules lists
--NOTE: we know 0 == "imported" / 1 == "interpreted" / 2 == "compiled" / 3 == "package" images
--TODO: move that to some kind of constants or so
let ims' = map (\m -> (0, [m, "Imported"])) ims
ms' = map (\m -> if HP.modInterpreted m
then (1, [HP.modName m, "Interpred"])
else (2, [HP.modName m, "Compiled"])) ms
pms' = map (\m -> (3, [m, "Package"])) $
flip filter pms $ \pm -> all (\xm -> HP.modName xm /= pm) ms
allms = zip [0..] (ims' ++ ms' ++ pms')
itemsDelete lstModules
(flip mapM) allms $ \(idx, (img, m@(mn:_))) ->
listCtrlInsertItemWithLabel lstModules idx mn img >>
set lstModules [item idx := m]
varSet varModsSel $ -1
-- Refresh the current text
set txtCode [text := t,
font := fontFixed]
-- Clean the status bar
set status [text := ""]
-- Refresh the current expression box
refreshExpr model guiCtx
runHP' :: HP.HPage () -> HPS.ServerHandle -> GUIContext -> IO ()
runHP' a = runHP $ a >>= return . Right
runHP :: HP.HPage (Either HP.InterpreterError ()) -> HPS.ServerHandle -> GUIContext -> IO ()
runHP hpacc model guiCtx@GUICtx{guiWin = win} =
do
res <- tryIn model hpacc
case res of
Left err ->
warningDialog win "Error" err
Right () ->
refreshPage model guiCtx
explain model guiCtx@GUICtx{guiWin = win,
guiResults = GUIRes{resValue = txtValue,
resErrors = varErrors}} =
do
sel <- textCtrlGetStringSelection txtValue
if sel == bottomChar || sel == bottomString
then do
txt <- get txtValue text
ip <- textCtrlGetInsertionPoint txtValue
errs <- varGet varErrors
let prevTxt = take ip txt
isBottom c = [c] == bottomChar || [c] == bottomString
errNo = length $ filter isBottom prevTxt
err = if length errs > errNo
then bottomDesc $ errs !! errNo
else "Unknown"
if sel == bottomChar
then errorDialog win "Bottom Char" err
else errorDialog win "Bottom String" err
else return ()
hayoo model guiCtx@GUICtx{guiCode = txtCode, guiWin = win} =
textCtrlGetStringSelection txtCode >>= hayooDialog win
interpret model guiCtx@GUICtx{guiResults = GUIRes{resLabel = lblInterpret,
resButton = btnInterpret,
resValue = txtValue,
res4Dots = lbl4Dots,
resType = txtType},
guiCode = txtCode,
guiCharTimer = charTimer,
guiWin = win,
guiChrVar = chv,
guiValFiller = vfv,
guiChrFiller = chfv} =
do
sel <- textCtrlGetStringSelection txtCode
let runner = case sel of
"" -> tryIn
sl -> runTxtHPSelection sl
refreshExpr model guiCtx
liftTraceIO "running..."
set txtValue [enabled := False,
bgcolor := lightgrey]
res <- runner model HP.interpret
liftTraceIO "ready"
case res of
Left err ->
warningDialog win "Error" err
Right interp ->
if HP.isIntType interp
then do
set txtValue [enabled := True,
bgcolor := white,
text := HP.intKind interp]
set lbl4Dots [visible := False]
set txtType [visible := False]
set lblInterpret [text := "Kind:"]
else do
set lbl4Dots [visible := True]
set txtType [visible := True, text := HP.intType interp]
set lblInterpret [text := "Value:"]
-- now we fill the textbox --
poc <- liftIO $ get btnInterpret $ on command
let revert = do
debugIO "Cancelling..."
tryTakeMVar chv --NOTE: empty the var
debugIO "Killing the char filler..."
newchf <- spawn $ charFiller guiCtx
swapMVar chfv newchf >>= kill
debugIO "Killing the value filler..."
newvf <- spawn $ valueFiller guiCtx
swapMVar vfv newvf >>= kill
debugIO "Ready"
set txtValue [enabled := True,
bgcolor := white]
set btnInterpret [on command := poc, text := "Interpret"]
in liftIO $ set btnInterpret [text := "Cancel",
on command := revert]
liftDebugIO "sending the value to the Value Filler..."
readMVar vfv >>= flip sendTo ((HP.intValue interp), poc)
runTxtHPSelection :: String -> HPS.ServerHandle ->
HP.HPage (Either HP.InterpreterError HP.Interpretation) -> IO (Either ErrorString HP.Interpretation)
runTxtHPSelection s model hpacc =
do
piRes <- tryIn' model HP.getPageIndex
added <- tryIn' model $ HP.addPage
case added of
Left err ->
return $ Left err
Right () ->
do
let cpi = case piRes of
Left err -> 0
Right cp -> cp
newacc = HP.setPageText s (length s) >> hpacc
res <- tryIn model newacc
tryIn' model $ HP.closePage >> HP.setPageIndex cpi
return res
refreshExpr :: HPS.ServerHandle -> GUIContext -> IO ()
refreshExpr model guiCtx@GUICtx{guiCode = txtCode,
guiWin = win,
guiTimer = refreshTimer} =
do
set txtCode [font := fontFixed] -- Just to be sure
txt <- get txtCode text
ip <- textCtrlGetInsertionPoint txtCode
res <- tryIn' model $ HP.setPageText txt ip
case res of
Left err ->
warningDialog win "Error" err
Right _ ->
debugIO "refreshExpr done"
timerStop refreshTimer
-- TIMER HANDLERS --------------------------------------------------------------
restartTimer model guiCtx@GUICtx{guiWin = win, guiTimer = refreshTimer} =
do
started <- timerStart refreshTimer 1000 True
if started
then return ()
else fail "Could not start more timers"
-- INTERNAL UTILS --------------------------------------------------------------
type ErrorString = String
tryIn' :: HPS.ServerHandle -> HP.HPage x -> IO (Either ErrorString x)
tryIn' model hpacc = tryIn model $ hpacc >>= return . Right
tryIn :: HPS.ServerHandle -> HP.HPage (Either HP.InterpreterError x) -> IO (Either ErrorString x)
tryIn model hpacc =
do
res <- HPS.runIn model $ catchError (hpacc >>= return . Right)
(\ioerr -> return $ Left ioerr)
case res of
Left err -> return . Left $ ioeGetErrorString err
Right (Left err) -> return . Left $ HP.prettyPrintError err
Right (Right val) -> return . Right $ val
-- FIND/REPLACE UTILS ----------------------------------------------------------
data FRFlags = FRFlags {frfGoingDown :: Bool,
frfMatchCase :: Bool,
frfWholeWord :: Bool,
frfWrapSearch :: Bool}
deriving (Eq, Show)
buildFRFlags :: Bool -> Int -> IO FRFlags
buildFRFlags w x = return FRFlags {frfGoingDown = (x .&. wxFR_DOWN) /= 0,
frfMatchCase = (x .&. wxFR_MATCHCASE) /= 0,
frfWholeWord = (x .&. wxFR_WHOLEWORD) /= 0,
frfWrapSearch = w}
openFindDialog :: HPS.ServerHandle -> GUIContext -> String -> Int -> IO ()
openFindDialog model guiCtx@GUICtx{guiWin = win,
guiSearch = search} title dlgStyle =
do
frdialog <- findReplaceDialogCreate win search title $ dlgStyle + wxFR_NOWHOLEWORD
let winSet k f = let hnd _ = f model guiCtx >> propagateEvent
in windowOnEvent frdialog [k] hnd hnd
winSet wxEVT_COMMAND_FIND findNextButton
winSet wxEVT_COMMAND_FIND_NEXT findNextButton
winSet wxEVT_COMMAND_FIND_REPLACE findReplaceButton
winSet wxEVT_COMMAND_FIND_REPLACE_ALL findReplaceAllButton
set frdialog [visible := True]
findNextButton, findReplaceButton, findReplaceAllButton :: HPS.ServerHandle -> GUIContext -> IO ()
findNextButton model guiCtx@GUICtx{guiCode = txtCode,
guiWin = win,
guiSearch = search} =
do
s <- findReplaceDataGetFindString search
fs <- findReplaceDataGetFlags search >>= buildFRFlags True
mip <- findMatch s fs txtCode
debugIO ("find/next", s, fs, mip)
case mip of
Nothing ->
infoDialog win "Find Results" $ s ++ " not found."
Just ip ->
do
textCtrlSetSelection txtCode (length s + ip) ip
refreshExpr model guiCtx
findReplaceButton model guiCtx@GUICtx{guiCode = txtCode,
guiWin = win,
guiSearch = search} =
do
s <- findReplaceDataGetFindString search
r <- findReplaceDataGetReplaceString search