File: HandleCommands.cpp

package info (click to toggle)
freemat 4.0-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 174,736 kB
  • ctags: 67,053
  • sloc: cpp: 351,060; ansic: 255,892; sh: 40,590; makefile: 4,323; perl: 4,058; asm: 3,313; pascal: 2,718; fortran: 1,722; ada: 1,681; ml: 1,360; cs: 879; csh: 795; python: 430; sed: 162; lisp: 160; awk: 5
file content (1526 lines) | stat: -rw-r--r-- 45,931 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
/*
 * Copyright (c) 2002-2006 Samit Basu
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "HandleCommands.hpp"
#include "HandleFigure.hpp"

#include "Parser.hpp"
#include "Scanner.hpp"
#include "Token.hpp"

#include <qgl.h>
#include <QtGui>
#include <QtSvg>
#include <cctype>
#include <algorithm>
#include "HandleLineSeries.hpp"
#include "HandleObject.hpp"
#include "HandleText.hpp"
#include "HandleAxis.hpp"
#include "HandleImage.hpp"
#include <qapplication.h>
#include "HandleList.hpp"
#include "HandleSurface.hpp"
#include "HandlePatch.hpp"
#include "HandleWindow.hpp"
#include "HandleContour.hpp"
#include "HandleUIControl.hpp"
#include "QTRenderEngine.hpp"
#include "Interpreter.hpp"
#include <math.h>

// Subplot
// labels don't always appear properly.
// linestyle/symbol specification
// images

QWidget *save = NULL;

void SaveFocus() {
  save = qApp->focusWidget();
}
  
void RestoreFocus() {
  if (save)
    save->setFocus();
}

HandleWindow* Hfigs[MAX_FIGS];
int HcurrentFig = -1;

static bool HGInitialized = false;

void InitializeHandleGraphics() {
  if (HGInitialized) return;
  for (int i=0;i<MAX_FIGS;i++) Hfigs[i] = NULL;
  HcurrentFig = -1;
  HGInitialized = true;
}

void ShutdownHandleGraphics() {
  for (int i=0;i<MAX_FIGS;i++) {
    if  (Hfigs[i]) {
      Hfigs[i]->hide();
      delete Hfigs[i];
    }
    Hfigs[i] = NULL;
  }
  HcurrentFig = -1;
}

// Magic constant - limits the number of figures you can have...
  
HandleList<HandleObject*> objectset;

void NotifyFigureClosed(unsigned figNum) {
  //    delete Hfigs[figNum];
  Hfigs[figNum] = NULL;
  if (((int)figNum) == HcurrentFig)
    HcurrentFig = -1;
  // Check for all figures closed
  bool allClosed = true;
  for (int i=0;allClosed && i<MAX_FIGS;i++)
    allClosed = Hfigs[i] == NULL;
}

void NotifyFigureActive(unsigned figNum) {
  HcurrentFig = figNum;
}

static void NewFig() {
  // First search for an unused fig number
  int figNum = 0;
  bool figFree = false;
  while ((figNum < MAX_FIGS) && !figFree) {
    figFree = (Hfigs[figNum] == NULL);
    if (!figFree) figNum++;
  }
  if (!figFree) {
    throw Exception("No more fig handles available!  Close some figs...");
  }
  Hfigs[figNum] = new HandleWindow(figNum);
  SaveFocus();
  Hfigs[figNum]->show();
  RestoreFocus();
  HcurrentFig = figNum;
}

static HandleWindow* CurrentWindow() {
  if (HcurrentFig == -1)
    NewFig();
  return (Hfigs[HcurrentFig]);
}

static HandleFigure* CurrentFig() {
  if (HcurrentFig == -1)
    NewFig();
  return (Hfigs[HcurrentFig]->HFig());
}


static void SelectFig(int fignum) {
  if (fignum < 0)
    throw Exception("Illegal argument to SelectFig");
  if (Hfigs[fignum] == NULL)
    Hfigs[fignum] = new HandleWindow(fignum);
  SaveFocus();
  Hfigs[fignum]->show();
  Hfigs[fignum]->raise();
  RestoreFocus();
  HcurrentFig = fignum;
}


bool AnyDirty() {
  bool retval = false;
  if (!HGInitialized) return false;
  for (int i=0;i<MAX_FIGS;i++) 
    if (Hfigs[i] && (Hfigs[i]->HFig()->isDirty()))  
      retval = true;
  return retval;
}

void RefreshFigs() {
  if (!GfxEnableFlag()) return;
  if (!HGInitialized) return;
  for (int i=0;i<MAX_FIGS;i++) {
    if (Hfigs[i] && (Hfigs[i]->HFig()->isDirty())) {
      Hfigs[i]->update();
    }
  }
}

static bool in_DoDrawNow = false;

static void DoDrawNow() {
  if (in_DoDrawNow) return;
  in_DoDrawNow = true;
  while (AnyDirty())
    qApp->processEvents(QEventLoop::AllEvents, 50);
  while (AnyDirty())  in_DoDrawNow = false;
}

//!
//@Module DRAWNOW Flush the Event Queue
//@@Section HANDLE
//@@Usage
//The @|drawnow| function can be used to process the events in the
//event queue of the FreeMat application.  The syntax for its use
//is
//@[
//   drawnow
//@]
//Now that FreeMat is threaded, you do not generally need to call this
//function, but it is provided for compatibility.
//@@Signature
//gfunction drawnow DrawNowFunction
//input none
//output none
//!
ArrayVector DrawNowFunction(int nargout, const ArrayVector& arg) {
  GfxEnableRepaint();
  DoDrawNow();
  GfxDisableRepaint();
  return ArrayVector();
}

HandleObject* LookupHandleObject(unsigned handle) {
  return (objectset.lookupHandle(handle-HANDLE_OFFSET_OBJECT));
}

HandleFigure* LookupHandleFigure(unsigned handle) {
  if (Hfigs[handle-HANDLE_OFFSET_FIGURE] != NULL)
    return Hfigs[handle-HANDLE_OFFSET_FIGURE]->HFig();
  else {
    SelectFig(handle-HANDLE_OFFSET_FIGURE);
    return Hfigs[handle-HANDLE_OFFSET_FIGURE]->HFig();
  }
}

void ValidateHandle(unsigned handle) {
  if (handle == 0) return;
  if (handle >= HANDLE_OFFSET_OBJECT)
    LookupHandleObject(handle);
  else
    LookupHandleFigure(handle);
}

unsigned AssignHandleObject(HandleObject* hp) {
  return (objectset.assignHandle(hp)+HANDLE_OFFSET_OBJECT);
}

void FreeHandleObject(unsigned handle) {
  objectset.deleteHandle(handle-HANDLE_OFFSET_OBJECT);
}


//!
//@Module FIGURE Figure Window Select and Create Function
//@@Section HANDLE
//@@Usage
//Changes the active figure window to the specified figure
//number.  The general syntax for its use is 
//@[
//  figure(number)
//@]
//where @|number| is the figure number to use. If the figure window 
//corresponding to @|number| does not already exist, a new 
//window with this number is created.  If it does exist
//then it is brought to the forefront and made active.
//You can use @|gcf| to obtain the number of the current figure.
//
//Note that the figure number is also the handle for the figure.
//While for most graphical objects (e.g., axes, lines, images), the
//handles are large integers, for figures, the handle is the same
//as the figure number.  This means that the figure number can be
//passed to @|set| and @|get| to modify the properties of the
//current figure, (e.g., the colormap).  So, for figure @|3|, for 
//example, you can use @|get(3,'colormap')| to retrieve the colormap
//for the current figure.
//@@Signature
//gfunction figure HFigureFunction
//input number
//output handle
//!
ArrayVector HFigureFunction(int nargout,const ArrayVector& arg) {
  if (arg.size() == 0) {
    NewFig();
    return ArrayVector(Array(double(HcurrentFig+1)));
  } else {
    Array t(arg[0]);
    int fignum = t.asInteger();
    if ((fignum<=0) || (fignum>MAX_FIGS))
      throw Exception("figure number is out of range - it must be between 1 and 50");
    SelectFig(fignum-1);
    return ArrayVector();
  }
}

void AddToCurrentFigChildren(unsigned handle) {
  HandleFigure *fig = CurrentFig();
  HPHandles *cp = (HPHandles*) fig->LookupProperty("children");
  QVector<unsigned> children(cp->Data());
  // Check to make sure that children does not contain our handle already
  int i=0;
  while (i<children.size()) {
    if (children[i] == handle)
      children.erase(children.begin()+i);
    else
      i++;
  }
  children.insert(children.begin(),1,handle);
  cp->Data(children);
}

//!
//@Module AXES Create Handle Axes
//@@Section HANDLE
//@@Usage
//This function has three different syntaxes.  The first takes
//no arguments,
//@[
//  h = axes
//@]
//and creates a new set of axes that are parented to the current
//figure (see @|gcf|).  The newly created axes are made the current
//axes (see @|gca|) and are added to the end of the list of children 
//for the current figure.
//The second form takes a set of property names and values
//@[
//  h = axes(propertyname,value,propertyname,value,...)
//@]
//Creates a new set of axes, and then sets the specified properties
//to the given value.  This is a shortcut for calling 
//@|set(h,propertyname,value)| for each pair.
//The third form takes a handle as an argument
//@[
//  axes(handle)
//@]
//and makes @|handle| the current axes, placing it at the head of
//the list of children for the current figure.
//@@Signature
//gfunction axes HAxesFunction
//input varargin
//output handle
//!
ArrayVector HAxesFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() != 1) {
    HandleObject *fp = new HandleAxis;
    unsigned int handle = AssignHandleObject(fp);
    ArrayVector t(arg);
    while (t.size() >= 2) {
      QString propname(t[0].asString());
      fp->LookupProperty(propname)->Set(t[1]);
      t.pop_front();
      t.pop_front();
    }
    // Get the current figure
    HandleFigure *fig = CurrentFig();
    fp->SetPropertyHandle("parent",HcurrentFig+1);
    fig->SetPropertyHandle("currentaxes",handle);
    // Add us to the children...
    AddToCurrentFigChildren(handle);
    fp->UpdateState();
    return ArrayVector(Array(double(handle)));
  } else {
    unsigned int handle = (unsigned int) arg[0].asInteger();
    HandleObject* hp = LookupHandleObject(handle);
    if (!hp->IsType("axes"))
      throw Exception("single argument to axes function must be handle for an axes"); 
    AddToCurrentFigChildren(handle);
    // Get the current figure
    CurrentFig()->SetPropertyHandle("currentaxes",handle);     
    CurrentFig()->UpdateState();
    return ArrayVector();
  }
}

void HSetChildrenFunction(HandleObject *fp, Array children) {
  children = children.toClass(UInt32);
  const BasicArray<uint32> &dp(children.constReal<uint32>());
  // make sure they are all valid handles
  for (index_t i=1;i<=dp.length();i++) 
    ValidateHandle(dp[i]);
  // Retrieve the current list of children
  HandleObject *gp;
  HPHandles *hp = (HPHandles*) fp->LookupProperty("children");
  QVector<unsigned> my_children(hp->Data());
  for (int i=0;i<my_children.size();i++) {
    unsigned handle = my_children[i];
    if (handle >= HANDLE_OFFSET_OBJECT) {
      gp = LookupHandleObject(handle);
      gp->Dereference();
    }
  }
  // Loop through the new list of children
  for (index_t i=1;i<=dp.length();i++) {
    unsigned handle = dp[i];
    if (handle >= HANDLE_OFFSET_OBJECT) {
      gp = LookupHandleObject(handle);
      gp->Reference();
    }
  }
  // Check for anyone with a zero reference count - it should
  // be deleted
  for (int i=0;i<my_children.size();i++) {
    unsigned handle = my_children[i];
    if (handle >= HANDLE_OFFSET_OBJECT) {
      gp = LookupHandleObject(handle);
      if (gp->RefCount() <= 0) {
	if (gp->StringPropertyLookup("type") == "uicontrol")
	  ((HandleUIControl*) gp)->Hide();
	FreeHandleObject(handle);
	delete gp;
      } 
    }
  }
  // Call the generic set function now
  hp->Set(children);
}


//!
//@Module SIZEFIG Set Size of Figure
//@@Section HANDLE
//@@Usage
//The @|sizefig| function changes the size of the currently
//selected fig window.  The general syntax for its use is
//@[
//   sizefig(width,height)
//@]
//where @|width| and @|height| are the dimensions of the fig
//window.
//@@Signature
//gfunction sizefig SizeFigFunction
//input width height
//output none
//!
ArrayVector SizeFigFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() < 2)
    throw Exception("sizefig requires width and height");
  int width = arg[0].asInteger();
  int height = arg[1].asInteger();
  QSize main_window_size = CurrentWindow()->size();
  QSize central_window_size = CurrentWindow()->centralWidget()->size();
  CurrentWindow()->resize(width + main_window_size.width() - central_window_size.width(),
			  height + main_window_size.height() - central_window_size.height());
  CurrentWindow()->HFig()->markDirty();
  return ArrayVector();
}

//!
//@Module SET Set Object Property
//@@Section HANDLE
//@@Usage
//This function allows you to change the value associated
//with a property.  The syntax for its use is
//@[
//  set(handle,property,value,property,value,...)
//@]
//where @|property| is a string containing the name of the
//property, and @|value| is the value for that property. The
//type of the variable @|value| depends on the property being
//set.  See the help for the properties to see what values
//you can set.
//@@Signature
//gfunction set HSetFunction
//input varargin
//output none
//!

static HandleObject* LookupObject(int handle) {
  if (handle <= 0)
    throw Exception("Illegal handle used for handle graphics operation");
  if (handle >= HANDLE_OFFSET_OBJECT)
    return LookupHandleObject(handle);
  else
    return ((HandleObject*) LookupHandleFigure(handle));
}

static void RecursiveUpdateState(int handle) {
  HandleObject *fp = LookupObject(handle);
  fp->UpdateState();
  HPHandles *children = (HPHandles*) fp->LookupProperty("children");
  QVector<unsigned> handles(children->Data());
  for (int i=0;i<handles.size();i++) {
    HandleObject *fp = LookupObject(handles[i]);
    fp->UpdateState();
  }  
}

ArrayVector HSetFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() < 3)
    throw Exception("set doesn't handle all cases yet!");
  int handle = arg[0].asInteger();
  // Lookup the handle
  HandleObject *fp = LookupObject(handle);
  int ptr = 1;
  while (arg.size() >= (ptr+2)) {
    // Use the address and property name to lookup the Get/Set handler
    QString propname = arg[ptr].asString();
    // Special case 'set' for 'children' - this can change reference counts
    // Special case 'set' for 'figsize' - this requires help from the OS
    if (propname == "children")
      HSetChildrenFunction(fp,arg[ptr+1]);
    else if ((handle < HANDLE_OFFSET_OBJECT) && (propname == "figsize")) {
      fp->LookupProperty(propname)->Set(arg[ptr+1]);
    } else {
      try {
	fp->LookupProperty(propname)->Set(arg[ptr+1]);
      } catch (Exception &e) {
	throw Exception(QString("Got error ") + QString(e.msg()) + 
			QString(" for property ") + propname);
      }
    }
    ptr+=2;
  }
  RecursiveUpdateState(handle);
  //  fp->UpdateState();
  if (!fp->IsType("figure") && !fp->IsType("uicontrol")) {
    //FIXME
    HandleFigure *fig = fp->GetParentFigure();
    fig->UpdateState();
    //     fig->Repaint();
  }
  CurrentWindow()->HFig()->markDirty();
  return ArrayVector();
}

//!
//@Module GET Get Object Property
//@@Section HANDLE
//@@Usage
//This function allows you to retrieve the value associated
//with a property.  The syntax for its use is
//@[
//  value = get(handle,property)
//@]
//where @|property| is a string containing the name of the
//property, and @|value| is the value for that property. The
//type of the variable @|value| depends on the property being
//set.  See the help for the properties to see what values
//you can set.
//@@Signature
//gfunction get HGetFunction
//input handle property
//output value
//!

ArrayVector HGetFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() != 2)
    throw Exception("get doesn't handle all cases yet!");
  int handle = arg[0].asInteger();
  QString propname = arg[1].asString();
  // Lookup the handle
  HandleObject *fp = LookupObject(handle);
  // Use the address and property name to lookup the Get/Set handler
  return ArrayVector(fp->LookupProperty(propname)->Get());
}

static unsigned GenericConstructor(HandleObject* fp, const ArrayVector& arg,
				   bool autoParentGiven = true) {
  unsigned int handle = AssignHandleObject(fp);
  ArrayVector t(arg);
  while (t.size() >= 2) {
    QString propname(t[0].asString());
    if (propname == "autoparent") {
      QString pval(t[1].asString());
      autoParentGiven = (pval == "on");
    }	else {
      try {
	fp->LookupProperty(propname)->Set(t[1]);
      } catch (Exception &e) {
	throw Exception(QString("Got error ") + e.msg() + 
			QString(" for property ") + propname);
      }
    }
    t.pop_front();
    t.pop_front();
  }
  if (autoParentGiven) {
    HandleFigure *fig = CurrentFig();
    unsigned current = fig->HandlePropertyLookup("currentaxes");
    if (current == 0) {
      ArrayVector arg2;
      HAxesFunction(0,arg2);
      current = fig->HandlePropertyLookup("currentaxes");
    }
    HandleAxis *axis = (HandleAxis*) LookupHandleObject(current);
    HPHandles *cp = (HPHandles*) axis->LookupProperty("children");
    QVector<unsigned> children(cp->Data());
    children.push_back(handle);
    cp->Data(children);
    cp = (HPHandles*) fp->LookupProperty("parent");
    QVector<unsigned> parent;
    parent.push_back(current);
    cp->Data(parent);
    axis->UpdateState();
    fig->markDirty();
  }
  fp->UpdateState();
  return handle;
}


//!
//@Module HLINE Create a line object
//@@Section HANDLE
//@@Usage
//Creates a line object and parents it to the current axis.  The
//syntax for its use is 
//@[
//  handle = hline(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current axis.
//@@Signature
//gfunction hline HLineFunction
//input varargin
//output handle
//!
ArrayVector HLineFunction(int nargout, const ArrayVector& arg) {
  return ArrayVector(Array(double(GenericConstructor(new HandleLineSeries,arg))));
}

//!
//@Module HCONTOUR Create a contour object
//@@Section HANDLE
//@@Usage
//Creates a contour object and parents it to the current axis.  The
//syntax for its use is 
//@[
//  handle = hcontour(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current axis.
//@@Signature
//gfunction hcontour HContourFunction
//input varargin
//output handle
//!
ArrayVector HContourFunction(int nargout, const ArrayVector& arg) {
  return ArrayVector(Array(double(GenericConstructor(new HandleContour,arg))));
}

//!
//@Module UICONTROL Create a UI Control object
//@@Section HANDLE
//@@Usage
//Creates a UI control object and parents it to the current figure.  The
//syntax for its use is
//@[
//  handle = uicontrol(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current figure.
//@@Signature
//sgfunction uicontrol HUIControlFunction
//input varargin
//output handle
//!
ArrayVector HUIControlFunction(int nargout, const ArrayVector& arg, Interpreter *eval) {
  HandleUIControl *o = new HandleUIControl;
  o->SetEvalEngine(eval);
  o->ConstructWidget(CurrentWindow());
  unsigned handleID = GenericConstructor(o,arg,false);
  // Parent the control to the current figure
  AddToCurrentFigChildren(handleID);
  HPHandles* cp = (HPHandles*) o->LookupProperty("parent");
  QVector<unsigned> parent;
  parent.push_back(HcurrentFig+1);
  cp->Data(parent);
  return ArrayVector(Array(double(handleID)));
}

//!
//@Module HIMAGE Create a image object
//@@Section HANDLE
//@@Usage
//Creates a image object and parents it to the current axis.  The
//syntax for its use is 
//@[
//  handle = himage(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current axis.
//@@Signature
//gfunction himage HImageFunction
//input varargin
//output handle
//!
ArrayVector HImageFunction(int nargout, const ArrayVector& arg) {
  return ArrayVector(Array(double(GenericConstructor(new HandleImage,arg))));
}

//!
//@Module HTEXT Create a text object
//@@Section HANDLE
//@@Usage
//Creates a text object and parents it to the current axis.  The
//syntax for its use is 
//@[
//  handle = htext(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current axis.
//@@Signature
//gfunction htext HTextFunction
//input varargin
//output handle
//!
ArrayVector HTextFunction(int nargout, const ArrayVector& arg) {
  return ArrayVector(Array(double(GenericConstructor(new HandleText,arg))));
}

//!
//@Module HSURFACE Create a surface object
//@@Section HANDLE
//@@Usage
//Creates a surface object and parents it to the current axis.  The
//syntax for its use is 
//@[
//  handle = hsurface(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current axis.
//@@Signature
//gfunction surface HSurfaceFunction
//input varargin
//output handle
//!
ArrayVector HSurfaceFunction(int nargout, const ArrayVector& arg) {
  return ArrayVector(Array(double(GenericConstructor(new HandleSurface,arg))));
}

//!
//@Module HPATCH Create a patch object
//@@Section HANDLE
//@@Usage
//Creates a patch object and parents it to the current axis.  The
//syntax for its use is 
//@[
//  handle = hpatch(property,value,property,value,...)
//@]
//where @|property| and @|value| are set.  The handle ID for the
//resulting object is returned.  It is automatically added to
//the children of the current axis.
//@@Signature
//gfunction hpatch HPatchFunction
//input varargin
//output handle
//!
ArrayVector HPatchFunction(int nargout, const ArrayVector& arg) {
  return ArrayVector(Array(double(GenericConstructor(new HandlePatch,arg))));
}


//!
//@Module FIGRAISE Raise a Figure Window
//@@Section HANDLE
//@@Usage
//Raises a figure window indicated by the figure number.  The syntax for
//its use is
//@[
//  figraise(fignum)
//@]
//where @|fignum| is the number of the figure to raise.  The figure will
//be raised to the top of the GUI stack (meaning that it we be visible).
//Note that this function does not cause @|fignum| to become the current
//figure, you must use the @|figure| command for that.
//@@Signature
//gfunction figraise FigRaiseFunction
//input handle
//output none
//!
ArrayVector FigRaiseFunction(int nargout, const ArrayVector& args) {
  if (args.size() == 0)
    CurrentWindow()->raise();
  else {
    int fignum = args[0].asInteger();
    if ((fignum >= 1) && (fignum < MAX_FIGS+1)) {
      if (Hfigs[fignum-1])
	Hfigs[fignum-1]->raise();
      else {
	Hfigs[fignum-1] = new HandleWindow(fignum-1);
	Hfigs[fignum-1]->show();
	Hfigs[fignum-1]->raise();
      }
    }
  }
  return ArrayVector();
}

//!
//@Module FIGLOWER Lower a Figure Window
//@@Section HANDLE
//@@Usage
//Lowers a figure window indicated by the figure number.  The syntax for
//its use is
//@[
//  figlower(fignum)
//@]
//where @|fignum| is the number of the figure to lower.  The figure will
//be lowerd to the bottom of the GUI stack (meaning that it we be behind other
//windows).  Note that this function does not cause @|fignum| to 
//become the current  figure, you must use the @|figure| command for that.
//Similarly, if @|fignum| is the current figure, it will remain the current
//figure (even though the figure is now behind others).
//@@Signature
//gfunction figlower FigLowerFunction
//input handle
//output none
//!
ArrayVector FigLowerFunction(int nargout, const ArrayVector& args) {
  if (args.size() == 0)
    CurrentWindow()->lower();
  else {
    int fignum = args[0].asInteger();
    if ((fignum >= 1) && (fignum < MAX_FIGS+1)) {
      if (Hfigs[fignum-1])
	Hfigs[fignum-1]->lower();
      else {
	Hfigs[fignum-1] = new HandleWindow(fignum-1);
	Hfigs[fignum-1]->show();
	Hfigs[fignum-1]->lower();
      }
    }
  }
  return ArrayVector();
}

//!
//@Module GCF Get Current Figure
//@@Section HANDLE
//@@Usage
//Returns the figure number for the current figure (which is also its handle,
//and can be used to set properties of the current figure using @|set|).  
//The syntax for its use
//is
//@[
//  figure_number = gcf
//@]
//where @|figure_number| is the number of the active figure (also the handle of
//the figure).
//
//Note that figures have handles, just like axes, images, plots, etc.  However
//the handles for figures match the figure number (while handles for other 
//graphics objects tend to be large, somewhat arbitrary integers).  So, to 
//retrieve the colormap of the current figure, you could 
//use @|get(gcf,'colormap')|, or to obtain the colormap for figure 3, 
//use @|get(3,'colormap')|.
//@@Signature
//gfunction gcf HGCFFunction
//input none
//output handle
//!
ArrayVector HGCFFunction(int nargout, const ArrayVector& arg) {
  if (HcurrentFig == -1)
    NewFig();      
  return ArrayVector(Array(double(HcurrentFig+1)));
}

//!
//@Module GCA Get Current Axis
//@@Section HANDLE
//@@Usage
//Returns the handle for the current axis.  The syntax for its use
//is
//@[
//  handle = gca
//@]
//where @|handle| is the handle of the active axis.  All object
//creation functions will be children of this axis.
//@@Signature
//gfunction gca HGCAFunction
//input none
//output handle
//!
ArrayVector HGCAFunction(int nargout, const ArrayVector& arg) {
  // Get the current figure...
  if (HcurrentFig == -1)
    NewFig();
  HandleFigure* fig = CurrentFig();
  unsigned current = fig->HandlePropertyLookup("currentaxes");
  if (current == 0) {
    ArrayVector arg2;
    HAxesFunction(0,arg2);
    current = fig->HandlePropertyLookup("currentaxes");
  }
  return ArrayVector(Array(double(current)));
}

//!
//@Module PVALID Validate Property Name
//@@Section HANDLE
//@@Usage
//This function checks to see if the given string is a valid
//property name for an object of the given type.  The syntax
//for its use is
//@[
//  b = pvalid(type,propertyname)
//@]
//where @|string| is a string that contains the name of a 
// valid graphics object type, and
//@|propertyname| is a string that contains the name of the
//property to test for.
//@@Example
//Here we test for some properties on an @|axes| object.
//@<
//pvalid('axes','type')
//pvalid('axes','children')
//pvalid('axes','foobar')
//@>
//@@Signature
//gfunction pvalid HPropertyValidateFunction
//input type property
//output bool
//!
ArrayVector HPropertyValidateFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() != 2)
    throw Exception("pvalid requires two arguments, an object type name and a property name");
  QString objectname = arg[0].asString();
  HandleObject *fp;
  if (objectname == "axes")
    fp = new HandleAxis;
  else if (objectname == "line")
    fp = new HandleLineSeries;
  else if (objectname == "text")
    fp = new HandleText;
  else if (objectname == "patch")
    fp = new HandlePatch;
  else
    throw Exception("Unrecognized object type name " + objectname);
  QString propname = arg[1].asString();
  bool isvalid;
  isvalid = true;
  try {
    fp->LookupProperty(propname);
  } catch (Exception& e) {
    isvalid = false;
  }
  delete fp;
  return ArrayVector(Array(bool(isvalid)));
}

bool PrintBaseFigure(HandleWindow* g, QString filename, 
		     QString type) {
  bool retval;
  HandleFigure* h = g->HFig();
  HPColor *color = (HPColor*) h->LookupProperty("color");
  double cr, cg, cb;
  cr = color->At(0); cg = color->At(1); cb = color->At(2);
  h->SetThreeVectorDefault("color",1,1,1);

  bool bRepaintFlag = GfxEnableFlag();

  GfxEnableRepaint();
  h->UpdateState();
  while (h->isDirty())
    qApp->processEvents(QEventLoop::AllEvents, 50);
  if ((type == "PDF") || (type == "PS") || (type == "EPS")){
    QPrinter prnt;
    if (type == "PDF")
      prnt.setOutputFormat(QPrinter::PdfFormat);
    else
      prnt.setOutputFormat(QPrinter::PostScriptFormat);
    prnt.setOutputFileName(filename);
    QPainter pnt(&prnt);
    QTRenderEngine gc(&pnt,0,0,g->width(),g->height());
    h->markDirty();
    h->PaintMe(gc);
    retval = true;
  } else if (type == "SVG") {
    QSvgGenerator gen;
    gen.setFileName(filename);
    gen.setSize(QSize(g->width(),g->height()));
    QPainter pnt(&gen);
    QTRenderEngine gc(&pnt,0,0,g->width(),g->height());
    h->PaintMe(gc);
    retval = true;
  } else {
    // Binary print - use grabWidget
    QPixmap pxmap(QPixmap::grabWidget(g->GetQtWidget()));
    QImage img(pxmap.toImage());
    retval = img.save(filename,type.toAscii().data());
  }
  h->SetThreeVectorDefault("color",cr,cg,cb);
  h->markDirty();
  while (h->isDirty())
    qApp->processEvents(QEventLoop::AllEvents, 50);
  if( !bRepaintFlag )
    GfxDisableRepaint();
  return retval;
}
  
void CloseHelper(int fig) {
  if (fig == -1) return;
  if (Hfigs[fig] == NULL) return;
  Hfigs[fig]->hide();
  delete Hfigs[fig];
  Hfigs[fig] = NULL;
  if (HcurrentFig == fig)
    HcurrentFig = -1;
}

//!
//@Module CLOSE Close Figure Window
//@@Section HANDLE
//@@Usage
//Closes a figure window, either the currently active window, a 
//window with a specific handle, or all figure windows.  The general
//syntax for its use is
//@[
//   close(handle)
//@]
//in which case the figure window with the speicified @|handle| is
//closed.  Alternately, issuing the command with no argument
//@[
//   close
//@]
//is equivalent to closing the currently active figure window.  Finally
//the command
//@[
//   close('all')
//@]
//closes all figure windows currently open.
//@@Signature
//gfunction close HCloseFunction
//input handle
//output none
//!
ArrayVector HCloseFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() > 1)
    throw Exception("close takes at most one argument - either the string 'all' to close all figures, or a scalar integer indicating which figure is to be closed.");
  int action;
  if (arg.size() == 0) 
    action = 0;
  else {
    Array t(arg[0]);
    if (t.isString()) {
      QString allflag = t.asString();
      if (allflag == "all") 
	action = -1;
      else
	throw Exception("string argument to close function must be 'all'");
    } else {
      int handle = t.asInteger();
      if (handle < 1)
	throw Exception("Invalid figure number argument to close function");
      action = handle;
    }
  }
  if (action == 0) {
    if (HcurrentFig != -1) 
      CloseHelper(HcurrentFig);
  } else if (action == -1) {
    for (int i=0;i<MAX_FIGS;i++)
      CloseHelper(i);
    HcurrentFig = -1;
  } else {
    if ((action < MAX_FIGS) && (action >= 1))
      CloseHelper(action-1);
  }
  return ArrayVector();
}

//!
//@Module COPY Copy Figure Window
//@@Section HANDLE
//@@Usage
//Copies the currently active figure window to the clipboard.
//The syntax for its use is:
//@[
//   copy
//@]
//The resulting figure is copied as a bitmap to the clipboard, 
//and can then be pasted into any suitable application.
//@@Signature
//gfunction copy HCopyFunction
//input none 
//output none
//!
ArrayVector HCopyFunction(int nargout, const ArrayVector& arg) {
  if (HcurrentFig == -1)
    return ArrayVector();
  HandleWindow *f = Hfigs[HcurrentFig];
  // use grabWidget - doesnt work for openGL yet
  QClipboard *cb = QApplication::clipboard();
  cb->setPixmap(QPixmap::grabWidget(f));
  return ArrayVector();
}
  
static QString NormalizeImageExtension(QString ext) {
  QString upperext(ext.toUpper());
  QString lowerext(ext.toLower());
  if (upperext == "JPG") return QString("JPEG");
  if ((upperext == "SVG") || (upperext == "PDF") || 
      (upperext == "PS") || (upperext == "EPS")) return upperext;
  QList<QByteArray> formats(QImageWriter::supportedImageFormats());
  for (int i=0;i<formats.count();i++) {
    if (formats.at(i).data() == upperext) return upperext;
    if (formats.at(i).data() == lowerext) return lowerext;
  }
  return QString();
}

QString FormatListAsString() {
  QString ret_text = "Supported Formats: ";
  QList<QByteArray> formats(QImageWriter::supportedImageFormats());
  for (int i=0;i<formats.count();i++)
    ret_text = ret_text + formats.at(i).data() + " ";
  return ret_text;
}

//!
//@Module PRINT Print a Figure To A File
//@@Section HANDLE
//@@Usage
//This function ``prints'' the currently active fig to a file.  The 
//generic syntax for its use is
//@[
//  print(filename)
//@]
//or, alternately,
//@[
//  print filename
//@]
//where @|filename| is the (string) filename of the destined file.  The current
//fig is then saved to the output file using a format that is determined
//by the extension of the filename.  The exact output formats may vary on
//different platforms, but generally speaking, the following extensions
//should be supported cross-platform:
//\begin{itemize}
//\item @|jpg|, @|jpeg|  --  JPEG file 
//\item @|pdf| -- Portable Document Format file
//\item @|png| -- Portable Net Graphics file
//\item @|svg| -- Scalable Vector Graphics file
//\end{itemize}
//Postscript (PS, EPS) is supported on non-Mac-OSX Unix only.
//Note that only the fig is printed, not the window displaying
//the fig.  If you want something like that (essentially a window-capture)
//use a seperate utility or your operating system's built in screen
//capture ability.
//@@Example
//Here is a simple example of how the figures in this manual are generated.
//@<
//x = linspace(-1,1);
//y = cos(5*pi*x);
//plot(x,y,'r-');
//print('printfig1.jpg')
//print('printfig1.png')
//@>
//which creates two plots @|printfig1.png|, which is a Portable
//Net Graphics file, and @|printfig1.jpg| which is a JPEG file.
//@figure printfig1
//@@Signature
//gfunction print HPrintFunction
//input varargin
//output none
//!
ArrayVector HPrintFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() != 1)
    throw Exception("print function takes a single, string argument");
  if (!(arg[0].isString()))
    throw Exception("print function takes a single, string argument");
  Array t(arg[0]);
  if (HcurrentFig == -1)
    return ArrayVector();
  HandleWindow *f = Hfigs[HcurrentFig];
  QString outname(t.asString());
  int pos = outname.lastIndexOf(".");
  if (pos < 0)
    throw Exception("print function argument must contain an extension - which is used to determine the format for the output");
  QString original_extension(outname.mid(pos+1,outname.size()));
  QString modified_extension = 
    NormalizeImageExtension(original_extension);
  if (modified_extension.isEmpty())
    throw Exception(QString("unsupported output format ") + 
		    original_extension + " for print.\n" + 
		    FormatListAsString());
  if (!PrintBaseFigure(f,outname,modified_extension))
    throw Exception("Printing failed!");
  return ArrayVector();
}

//!
//@Module HTEXTBITMAP Get Text Rendered as a Bitmap
//@@Section HANDLE
//@@Usage
//This function takes a fontname, a size, and a text string
//and returns a bitmap containing the text.  The generic syntax
//for its use is
//@[
//  bitmap = htextbitmap(fontname,size,text)
//@]
//where the output bitmap contains the text rendered into a matrix.
//@@Signature
//gfunction htextbitmap HTextBitmapFunction
//input fontname size text
//output bitmap
//!
const int m_pad = 10;
ArrayVector HTextBitmapFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() < 3) throw Exception("htextbitmap requires three arguments");
  QString fontname(arg[0].asString());
  int fontsize(arg[1].asInteger());
  QString fonttext(arg[2].asString());
  QFont fnt(fontname,fontsize);
  QFontMetrics fmet(fnt);
  int ascent = fmet.ascent();
  int descent = fmet.descent();
  int height = ascent + descent + 1;
  int width = fmet.width(fonttext);
  QImage img(width,height,QImage::Format_RGB32);
  QPainter pnt(&img);
  pnt.setPen(QColor(Qt::black));
  pnt.setBrush(QColor(Qt::black));
  pnt.drawRect(0,0,width,height);
  pnt.setPen(QColor(Qt::white));
  pnt.setBrush(QColor(Qt::white));
  pnt.setFont(fnt);
  pnt.drawText(0,height-descent-1,fonttext);
  Array M(UInt8,NTuple(height,width));
  BasicArray<uint8> &val(M.real<uint8>());
  for (int i=0;i<width;i++)
    for (int j=0;j<height;j++) {
      QRgb p = img.pixel(i,j);
      val[NTuple(j+1,i+1)] = qGray(p);
    }
  return ArrayVector(M);
}

//!
//@Module HRAWPLOT Generate a Raw Plot File
//@@Section HANDLE
//@@Usage
//This function takes a sequence of commands, and generates
//a raw plot (to a file) that renders the commands.  It is 
//a useful tool for creating high quality fully customized 
//PDF plots from within FreeMat scripts that are portable.  The
//syntax for its use 
//@[
//  hrawplot(filename,commands)
//@]
//where @|filename| is the name of the file to plot to, 
//and @|commands| is a cell array of strings.  Each entry in the 
//cell array contains a string with a command text.  The
//commands describe a simple mini-language for describing
//plots.  The complete dictionary of commands is given
//\begin{itemize}
//\item @|LINE x1 y1 x2 y2| -- draw a line
//\item @|FONT name size| -- select a font of the given name and size
//\item @|TEXT x1 y1 string| -- draw the given text string at the given location
//\item @|STYLE style| -- select line style ('solid' or 'dotted')
//\item @|PAGE| -- force a new page
//\item @|SIZE x1 y1| -- Set the page mapping
//\end{itemize}
//@@Signature
//gfunction hrawplot HRawPlotFunction
//input filename commands
//output none
//!

ArrayVector HRawPlotFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() < 2) throw Exception("hrawplot requires 4 arguments");
  QString filename(arg[0].asString());
  if (arg[1].dataClass() != CellArray) throw Exception("Expect a cell array of commands.");
  if (!filename.endsWith(".pdf")) throw Exception("filename must end with PDF");
  QPrinter prnt;
  prnt.setOutputFormat(QPrinter::PdfFormat);
  prnt.setOutputFileName(filename);
  prnt.setPageSize(QPrinter::Ledger);
  QPainter pnt(&prnt);
  QRect rect = pnt.viewport();
  const BasicArray<Array>& dp(arg[1].constReal<Array>());
  int descent = 0;
  for (index_t i=1;i<=dp.length();i++) {
    ArrayVector cmdp(ArrayVectorFromCellArray(dp[i]));
    QString cmd = QString("%1 %2").arg(cmdp[0].asString()).arg(int(i));
    if (cmdp[0].asString().toUpper() == "LINE") {
      if (cmdp.size() != 5) throw Exception("malformed line: " + cmd);
      int x1 = cmdp[1].asInteger();
      int y1 = cmdp[2].asInteger();
      int x2 = cmdp[3].asInteger();
      int y2 = cmdp[4].asInteger();
      pnt.drawLine(x1,y1,x2,y2);
    } else if (cmdp[0].asString().toUpper() == "FONT") {
      if (cmdp.size() != 3) throw Exception("malformed line: " + cmd);
      QString name = cmdp[1].asString();
      int size = cmdp[2].asInteger();
      QFont fnt(name,size);
      QFontMetrics metrics(fnt);
      descent = metrics.descent();
      pnt.setFont(QFont(name,size));
    } else if (cmdp[0].asString().toUpper() == "TEXT") {
      if (cmdp.size() != 4) throw Exception("malformed line: " + cmd);
      int x1 = cmdp[1].asInteger();
      int y1 = cmdp[2].asInteger();
      QString txt = cmdp[3].asString();
      pnt.drawText(x1,y1-descent,txt);
    } else if (cmdp[0].asString().toUpper() == "STYLE") {
      if (cmdp.size() != 2) throw Exception("malformed line: " + cmd);
      QString style = cmdp[1].asString();
      if (style.toUpper() == "SOLID")
	pnt.setPen(Qt::SolidLine);
      else if (style.toUpper() == "DOTTED")
	pnt.setPen(Qt::DotLine);
      else
	throw Exception("malformed line: " + cmd);
    } else if (cmdp[0].asString().toUpper() == "PAGE") {
      prnt.newPage();
    } else if (cmdp[0].asString().toUpper() == "SIZE") {
      if (cmdp.size() != 3) throw Exception("malformed line: " + cmd);
      int width = cmdp[1].asInteger();
      int height = cmdp[2].asInteger();
      QSize size(width,height);
      size.scale(rect.size(),Qt::KeepAspectRatio);
      pnt.setViewport(rect.x() + (rect.width()-size.width())/2,
		      rect.y() + (rect.height()-size.height())/2,
		      size.width(),size.height());
      pnt.setWindow(QRect(0,0,width,height));
      pnt.eraseRect(0,0,width,height);
    } else
      throw Exception("malformed line: " + cmd);
  }
  return ArrayVector();
}


//!
//@Module HPOINT Get Point From Window
//@@Section HANDLE
//@@Usage
//This function waits for the user to click on the current figure
//window, and then returns the coordinates of that click.  The
//generic syntax for its use is
//@[
//  [x,y] = hpoint
//@]
//@@Signature
//gfunction hpoint HPointFunction
//input none
//output coords
//!
ArrayVector HPointFunction(int nargout, const ArrayVector& arg) {
  if (HcurrentFig == -1)
    return ArrayVector();
  HandleWindow *f = Hfigs[HcurrentFig];
  f->raise();
  f->activateWindow();
  f->setFocus(Qt::OtherFocusReason);
  int x, y;
  GfxEnableRepaint();
  f->GetClick(x,y);
  GfxDisableRepaint();
  BasicArray<double> retvec(NTuple(2,1));
  retvec.set(1,x);
  retvec.set(2,y);
  return ArrayVector(Array(retvec));
}

//!
//@Module IS2DVIEW Test Axes For 2D View
//@@Section HANDLE
//@@Usage
//This function returns @|true| if the current axes are in a
//2-D view, and false otherwise.  The generic syntax for its
//use is
//@[
//  y = is2dview(x)
//@]
//where @|x| is the handle of an axes object.
//@@Signature
//gfunction is2dview HIs2DViewFunction
//input handle
//output bool
//!
ArrayVector HIs2DViewFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() == 0) throw Exception("is2DView expects a handle to axes");
  unsigned int handle = (unsigned int) (arg[0].asInteger());
  HandleObject* hp = LookupHandleObject(handle);
  if (!hp->IsType("axes"))
    throw Exception("single argument to axes function must be handle for an axes"); 
  HandleAxis *axis = (HandleAxis*) hp;
  return ArrayVector(Array(bool(axis->Is2DView())));
}

#if 0
class contour_point {
public:
  double x;
  double y;
  inline contour_point(double a, double b) : x(a), y(b) {};
};

inline bool operator==(const contour_point& p1, const contour_point& p2) {
  return ((p1.x == p2.x) && (p1.y == p2.y));
}

typedef QList<contour_point> cline;
typedef QList<cline> lineset;

inline cline Reverse(const cline& src) {
  cline ret;
  for (int i=src.size()-1;i>=0;i--)
    ret << src.at(i);
  return ret;
}

inline bool Connected(const cline& current, const cline& test) {
  return ((current.front() == test.front()) || 
	  (current.front() == test.back()) ||
	  (current.back() == test.front()) ||
	  (current.back() == test.back()));
}

inline void Join(cline& current, const cline& toadd) {
  if (current.front() == toadd.front())
    current = Reverse(toadd) + current;
  else if (current.front() == toadd.back())
    current = toadd + current;
  else if (current.back() == toadd.front())
    current += toadd;
  else if (current.back() == toadd.back())
    current += Reverse(toadd);
}

#define FOLD(x) MAP((x),row-1)
#define FNEW(x) MAP((x),row)
#define MAP(x,y) func[(y)+(x)*numy]
#define AINTER(a,b) ((val-(a))/((b)-(a)))
#define ALEFT(i,j) (((j)-1)+AINTER(FOLD((i)-1),FNEW((i)-1)))
#define TOP(i) (((i)-1)+AINTER(FNEW((i)-1),FNEW((i))))
#define BOT(i) (((i)-1)+AINTER(FOLD((i)-1),FOLD((i))))
#define RIGHT(i,j) (((j)-1)+AINTER(FOLD((i)),FNEW((i))))
#define DRAW(a,b,c,d) {allLines << (cline() << contour_point((double)a,(double)b) << contour_point((double)c,(double)d));}

ArrayVector ContourCFunction(int nargout, const ArrayVector& arg) {
  lineset allLines;
  lineset bundledLines;
  if (arg.size() < 2) throw Exception("contourc expects two arguments");
  double val = arg[1].asDouble();
  if (!arg[0].is2D())
    throw Exception("First argument to contourc must be a 2D matrix");
  Array m(arg[0].toClass(Double));
  const double *func = (const double *) m.getDataPointer();
  int outcnt = 0;
  int numy = m.rows();
  int numx = m.columns();
  for (int row=1;row<numy;row++)
    for (int col=1;col<numx;col++) {
      int l = 0;
      if (FOLD(col) >= val) l  = l + 1;
      if (FOLD(col-1) >= val) l = l + 2;
      if (FNEW(col) >= val) l = l + 4;
      if (FNEW(col-1) >= val) l = l + 8;
      switch (l) {
      case 1:
      case 14:
	DRAW(BOT(col),row-1,col,RIGHT(col,row));
	break;
      case 2:
      case 13:
	DRAW(col-1,ALEFT(col,row),BOT(col),row-1);
	break;
      case 3:
      case 12:
	DRAW(col-1,ALEFT(col,row),col,RIGHT(col,row));
	break;
      case 4:
      case 11:
	DRAW(TOP(col),row,col,RIGHT(col,row));
	break;
      case 5:
      case 10:
	DRAW(BOT(col),row-1,TOP(col),row);
	break;
      case 6:
      case 9:
	{
	  double x0 = AINTER(FOLD(col-1),FOLD(col));
	  double x1 = AINTER(FNEW(col-1),FNEW(col));
	  double y0 = AINTER(FOLD(col-1),FNEW(col-1));
	  double y1 = AINTER(FOLD(col),FNEW(col));
	  double y = (x0*(y1-y0)+y0)/(1.0-(x1-x0)*(y1-y0));
	  double x = y*(x1-x0) + x0;
	  double fx1 = MAP(col-1,row-1)+x*(MAP(col,row-1)-MAP(col-1,row-1));
	  double fx2 = MAP(col-1,row)+x*(MAP(col,row)-MAP(col-1,row));
	  double f = fx1 + y*(fx2-fx1);
	  if (f==val) {
	    DRAW(BOT(col),row-1,TOP(col),row);
	    DRAW(col-1,ALEFT(col,row),col,RIGHT(col,row));
	  } else if (((f > val) && (FNEW(col) > val)) || 
		     ((f < val) && (FNEW(col) < val))) {
	    DRAW(col-1,ALEFT(col,row),TOP(col),row);
	    DRAW(BOT(col),row-1,col,RIGHT(col,row));
	  } else {
	    DRAW(col-1,ALEFT(col,row),BOT(col),row-1);
	    DRAW(TOP(col),row,col,RIGHT(col,row));
	  }
	}
	break;
      case 7:
      case 8:
	DRAW(col-1,ALEFT(col,row),TOP(col),row);
	break;
      }
    }
  // Now we link the line segments into longer lines.
  int allcount = allLines.size();
  while (!allLines.empty()) {
    // Start a new line segment
    cline current(allLines.takeAt(0));
    bool lineGrown = true;
    while (lineGrown) {
      lineGrown = false;
      int i = 0;
      while (i<allLines.size()) {
	if (Connected(current,allLines.at(i))) {
	  Join(current,allLines.takeAt(i));
	  lineGrown = true;
	} else
	  i++;
      }
    }
    bundledLines << current;
  }
  int outcount = bundledLines.size() + 2*allcount + 1;
  Array out(Array::doubleMatrixConstructor(2,outcount));
  double *output = (double *) out.getReadWriteDataPointer();
  for (int i=0;i<bundledLines.size();i++) {
    *output++ = val;
    *output++ = bundledLines[i].size();
    cline bline(bundledLines[i]);
    for (int j=0;j<bline.size();j++) {
      *output++ = bline[j].x;
      *output++ = bline[j].y;
    }
  }
  return ArrayVector() << out;
}
#endif 

void LoadHandleGraphicsFunctions(Context* context) {
  InitializeHandleGraphics();
};