summaryrefslogtreecommitdiff
path: root/library/applnk.cpp
blob: a56da5d33594c204bf39d5c2daab97e2b135f026 (plain)
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
/**********************************************************************
** Copyright (C) 2000-2002 Trolltech AS.  All rights reserved.
**
** This file is part of the Qtopia Environment.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/

#define QTOPIA_INTERNAL_MIMEEXT
#define QTOPIA_INTERNAL_PRELOADACCESS
#define QTOPIA_INTERNAL_APPLNKASSIGN

#include "applnk.h"

#include <qpe/qpeapplication.h>
#include <qpe/categories.h>
#include <qpe/categoryselect.h>
#ifdef QWS
#include <qpe/qcopenvelope_qws.h>
#endif
#include <qpe/global.h>
#include <qpe/mimetype.h>
#include <qpe/config.h>
#include <qpe/storage.h>
#include <qpe/resource.h>

#include <qdict.h>
#include <qdir.h>
#include <qregexp.h>

#ifdef Q_WS_QWS
#include <qgfx_qws.h>
#endif

#include <stdlib.h>

int AppLnk::lastId = 5000;

static int smallSize = 14;
static int bigSize = 32;

static QString safeFileName(const QString& n)
{
    QString safename=n;
    safename.replace(QRegExp("[^0-9A-Za-z.]"),"_");
    safename.replace(QRegExp("^[^A-Za-z]*"),"");
    if ( safename.isEmpty() )
	safename = "_";
    return safename;
}

static bool prepareDirectories(const QString& lf)
{
    if ( !QFile::exists(lf) ) {
	// May need to create directories
	QFileInfo fi(lf);
	if ( system(("mkdir -p "+fi.dirPath(TRUE))) )
	    return FALSE;
    }
    return TRUE;
}

class AppLnkPrivate
{
public:
    /* the size of the Pixmap */
    enum Size {Normal = 0, Big };
    AppLnkPrivate() {
        /* we want one normal and one big item */

        QPixmap pix;
        mPixmaps.insert(0, pix );
        mPixmaps.insert(1,  pix);
    }

    QStringList mCatList; // always correct
    QArray<int> mCat; // cached value; correct if not empty
    QMap<int,  QPixmap> mPixmaps;

    void updateCatListFromArray()
    {
	Categories cat( 0 );
	cat.load( categoryFileName() );
	mCatList = cat.labels("Document View",mCat);
    }

    void setCatArrayDirty()
    {
	mCat.resize(0);
    }

    void ensureCatArray()
    {
	if ( mCat.count() > 0 || mCatList.count()==0 )
	    return;

	Categories cat( 0 );
	cat.load( categoryFileName() );
	mCat.resize( mCatList.count() );
	int i;
	QStringList::ConstIterator it;
	for ( i = 0, it = mCatList.begin(); it != mCatList.end();
	      ++it, i++ ) {

	    bool number;
	    int id = (*it).toInt( &number );
	    if ( !number ) {
		id = cat.id( "Document View", *it );
		if ( id == 0 )
		    id = cat.addCategory( "Document View", *it );
	    }
	    mCat[i] = id;
	}
    }
};

/*!
  \class AppLnk applnk.h
  \brief The AppLnk class represents an application available on the system.

    Every Qtopia application \e app has a corresponding \e app.desktop
    file. When one of these files is read its data is stored as an
    AppLnk object.

    The AppLnk class introduces some Qtopia-specific concepts, and
    provides a variety of functions, as described in the following
    sections.
    \tableofcontents

    \target Types
    \section1 Types

    Every AppLnk object has a \e type. For applications, games and
    settings the type is \c Application; for documents the
    type is the document's MIME type.

    \target files-and-links
    \section1 Files and Links

    When you create an AppLnk (or more likely, a \link doclnk.html
    DocLnk\endlink), you don't deal directly with filenames in the
    filesystem. Instead you do this:
    \code
    DocLnk d;
    d.setType("text/plain");
    d.setName("My Nicely Named Document / Whatever"); // Yes, "/" is legal.
    \endcode
    At this point, the file() and linkFile() are unknown. Normally
    this is uninteresting, and the names become automatically known,
    and more importantly, becomes reserved, when you ask what they are:

    \code
    QString fn = d.file();
    \endcode
    This invents a filename, and creates the file on disk (an empty
    reservation file) to prevent the name being used by another
    application.

    In some circumstances, you don't want to create the file if it
    doesn't already exist (e.g. in the Document tab, some of the \link
    doclnk.html DocLnk\endlink objects represented by icons are
    DocLnk's created just for that view - they don't have
    corresponding \c .desktop files. To avoid littering empty
    reservation files around, we check in a few places to see whether
    the file really needs to exist).

    \section1 Functionality

    AppLnk objects are created by calling the constructor with the
    name of a \e .desktop file. The object can be checked for validity
    using isValid().

    The following functions are used to set or retrieve information
    about the application:
    \table
    \header \i Get Function \i Set Function \i Short Description
    \row \i \l name()	    \i \l setName()    \i application's name
    \row \i \l pixmap()     \i \e none	    \i application's icon
    \row \i \l bigPixmap()  \i \e none	    \i application's large icon
    \row \i \e none	    \i setIcon()    \i sets the icon's filename
    \row \i \l type() 	    \i \l setType()    \i see \link #Types Types\endlink above
    \row \i \l rotation()   \i \e none	    \i 0, 90, 180 or 270 degrees
    \row \i \l comment()    \i \l setComment() \i text for the Details dialog
    \row \i \l exec()	    \i \l setExec()    \i executable's filename
    \row \i \l file()	    \i \e none	    \i document's filename
    \row \i \l linkFile()   \i \l setLinkFile()	\i \e .desktop filename
    \row \i \l mimeTypes()  \i \e none	    \i the mime types the application can view or edit
    \row \i \l categories() \i \l setCategories()	\i \e{see the function descriptions}
    \row \i \l fileKnown()  \i \e none	    \i see \link
#files-and-links Files and Links\endlink above
    \row \i \l linkFileKnown() \i \e none	    \i see \link
#files-and-links Files and Links\endlink above
    \row \i \l property()   \i \l setProperty()	\i any AppLnk property
    can be retrieved or set (if writeable) using these
    \endtable

    To save an AppLnk to disk use writeLink(). To execute the
    application that the AppLnk object refers to, use execute().

    AppLnk's can be deleted from disk using removeLinkFile(). To
    remove both the link and the application's executable use
    removeFiles().

    Icon sizes can be globally changed (but only for AppLnk objects
    created after the calls) with setSmallIconSize() and
    setBigIconSize().

    \ingroup qtopiaemb
*/

/*!
  Sets the size used for small icons to \a small pixels.
  Only affects AppLnk objects created after the call.

  \sa smallIconSize() setIcon()
*/
void AppLnk::setSmallIconSize(int small)
{
    smallSize = small;
}

/*!
  Returns the size used for small icons.

  \sa setSmallIconSize() setIcon()
*/
int AppLnk::smallIconSize()
{
    return smallSize;
}


/*!
  Sets the size used for large icons to \a big pixels.
  Only affects AppLnk objects created after the call.

  \sa bigIconSize() setIcon()
*/
void AppLnk::setBigIconSize(int big)
{
    bigSize = big;
}

/*!
  Returns the size used for large icons.

  \sa setBigIconSize() setIcon()
*/
int AppLnk::bigIconSize()
{
    return bigSize;
}


/*!
  \fn QString AppLnk::name() const

  Returns the Name property. This is the user-visible name for the
  document or application, not the filename.

    See \link #files-and-links Files and Links\endlink.

  \sa setName()
*/
/*!
    \fn QString AppLnk::exec() const

  Returns the Exec property. This is the name of the executable
  program associated with the AppLnk.

  \sa setExec()
*/
/*!
    \fn QString AppLnk::rotation() const

  Returns the Rotation property. The value is 0, 90, 180 or 270
  degrees.
*/
/*!
    \fn QString AppLnk::comment() const

  Returns the Comment property.

  \sa setComment()
*/
/*!
    \fn QStringList AppLnk::mimeTypes() const

  Returns the MimeTypes property. This is the list of MIME types
  that the application can view or edit.
*/
/*!
    \fn const QArray<int>& AppLnk::categories() const

  Returns the Categories property.

  See the CategoryWidget for more details.

  \sa setCategories()
*/

const QArray<int>& AppLnk::categories() const
{
    d->ensureCatArray();
    return d->mCat;
}

/*!
    \fn int AppLnk::id() const

  Returns the id of the AppLnk. If the AppLnk is not in an AppLnkSet,
  this value is 0, otherwise it is a value that is unique for the
  duration of the current process.

  \sa AppLnkSet::find()
*/

/*!
  \fn bool AppLnk::isValid() const

  Returns TRUE if this AppLnk is valid; otherwise returns FALSE.
*/

/*!
  Creates an invalid AppLnk.

  \sa isValid()
*/
AppLnk::AppLnk()
{
    mId = 0;
    d = new AppLnkPrivate();
}

/*!
  Loads \a file (e.g. \e app.desktop) as an AppLnk.

  \sa writeLink()
*/
AppLnk::AppLnk( const QString &file )
{
    QStringList sl;
    d = new AppLnkPrivate();
    if ( !file.isNull() ) {
	Config config( file, Config::File );

	if ( config.isValid() ) {
	    config.setGroup( "Desktop Entry" );

	    mName = config.readEntry( "Name", file );
	    mExec = config.readEntry( "Exec" );
	    mType = config.readEntry( "Type", QString::null );
	    mIconFile = config.readEntry( "Icon", QString::null );
	    mRotation = config.readEntry( "Rotation", "" );
	    mComment = config.readEntry( "Comment", QString::null );
	    // MIME types are case-insensitive.
	    mMimeTypes = config.readListEntry( "MimeType", ';' );
	    for (QStringList::Iterator it=mMimeTypes.begin(); it!=mMimeTypes.end(); ++it)
		*it = (*it).lower();
	    mMimeTypeIcons = config.readListEntry( "MimeTypeIcons", ';' );
	    mLinkFile = file;
	    mFile = config.readEntry("File", QString::null);
	    if ( !mExec. isEmpty ( )) {
		mFile = QString::null;
	    }
	    else if ( mFile[0] != '/' ) {
		int slash = file.findRev('/');
		if ( slash >= 0 ) {
		    mFile = file.left(slash) + '/' + mFile;
		}
	    }
	    d->mCatList = config.readListEntry("Categories", ';');
	    if ( d->mCatList[0].toInt() < -1 ) {
		// numeric cats in file! convert to text
		Categories cat( 0 );
		cat.load( categoryFileName() );
		d->mCat.resize( d->mCatList.count() );
		int i;
		QStringList::ConstIterator it;
		for ( i = 0, it = d->mCatList.begin(); it != d->mCatList.end();
		      ++it, i++ ) {
		    bool number;
		    int id = (*it).toInt( &number );
		    if ( !number ) {
			// convert from text
			id = cat.id( "Document View", *it );
			if ( id == 0 )
			    id = cat.addCategory( "Document View", *it );
		    }
		    d->mCat[i] = id;
		}
		d->updateCatListFromArray();
	    }
	}
    }
    mId = 0;
}

AppLnk& AppLnk::operator=(const AppLnk &copy)
{
    if ( mId )
	qWarning("Deleting AppLnk that is in an AppLnkSet");
    if ( d )
	delete d;


    mName = copy.mName;

    /* remove for Qtopia 3.0 -zecke */
    mPixmap = copy.mPixmap;
    mBigPixmap = copy.mBigPixmap;

    mExec = copy.mExec;
    mType = copy.mType;
    mRotation = copy.mRotation;
    mComment = copy.mComment;
    mFile = copy.mFile;
    mLinkFile = copy.mLinkFile;
    mIconFile = copy.mIconFile;
    mMimeTypes = copy.mMimeTypes;
    mMimeTypeIcons = copy.mMimeTypeIcons;
    mId = 0;
    d = new AppLnkPrivate();
    d->mCat = copy.d->mCat;
    d->mCatList = copy.d->mCatList;
    d->mPixmaps = copy.d->mPixmaps;

    return *this;
}
/*!
  protected internally to share code
  should I document that at all?
  I don't know the TT style for that
*/
const QPixmap& AppLnk::pixmap( int pos, int size ) const {
    if ( d->mPixmaps[pos].isNull() ) {
	AppLnk* that = (AppLnk*)this;
	if ( mIconFile.isEmpty() ) {
	    MimeType mt(type());
	    that->d->mPixmaps[pos] = mt.pixmap();
	    if ( that->d->mPixmaps[pos].isNull() )
		that->d->mPixmaps[pos].convertFromImage(
		    Resource::loadImage("UnknownDocument")
			.smoothScale( size, size ) );
	    return that->d->mPixmaps[pos];
	}
	QImage unscaledIcon = Resource::loadImage( that->mIconFile );
	if ( unscaledIcon.isNull() ) {
	    qDebug( "Cannot find icon: %s", that->mIconFile.latin1() );
	    that->d->mPixmaps[pos].convertFromImage(
		    Resource::loadImage("UnknownDocument")
			.smoothScale( size, size ) );
	} else {
	    that->d->mPixmaps[0].convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) );
	    that->d->mPixmaps[1].convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) );
	}
	return that->d->mPixmaps[pos];
    }
    return d->mPixmaps[pos];
}

/*!
  Returns a small pixmap associated with the application.

  \sa bigPixmap() setIcon()
*/
const QPixmap& AppLnk::pixmap() const
{
    if ( d->mPixmaps[0].isNull() ) {
        return pixmap(AppLnkPrivate::Normal, smallSize );
    }
    return d->mPixmaps[0];
}

/*!
  Returns a large pixmap associated with the application.

  \sa pixmap() setIcon()
*/
const QPixmap& AppLnk::bigPixmap() const
{
    if ( d->mPixmaps[1].isNull() ) {
        return pixmap( AppLnkPrivate::Big, bigSize );
    }
    return d->mPixmaps[1];
}

/*!
  Returns the type of the AppLnk. For applications, games and
  settings the type is \c Application; for documents the type is the
  document's MIME type.
*/
QString AppLnk::type() const
{
    if ( mType.isNull() ) {
	AppLnk* that = (AppLnk*)this;
	QString f = file();
	if ( !f.isNull() ) {
	    MimeType mt(f);
	    that->mType = mt.id();
	    return that->mType;
	}
    }
    return mType;
}

/*!
  Returns the file associated with the AppLnk.

  \sa exec() name()
*/
QString AppLnk::file() const
{
    if ( mExec.isEmpty ( ) && mFile.isNull() ) {
	AppLnk* that = (AppLnk*)this;
	QString ext = MimeType(mType).extension();
	if ( !ext.isEmpty() )
	    ext = "." + ext;
	if ( !mLinkFile.isEmpty() ) {
	    that->mFile =
		mLinkFile.right(8)==".desktop" // 8 = strlen(".desktop")
		    ? mLinkFile.left(mLinkFile.length()-8) : mLinkFile;
	qDebug("mFile now == %s", mFile.latin1());
	} else if ( mType.contains('/') ) {
	    that->mFile =
		QString(getenv("HOME"))+"/Documents/"+mType+"/"+safeFileName(that->mName);
            /*
             * A file with the same name or a .desktop file already exists
             */
	    if ( QFile::exists(that->mFile+ext) || QFile::exists(that->mFile+".desktop") ) {
		int n=1;
		QString nn;
		while (QFile::exists((nn=(that->mFile+"_"+QString::number(n)))+ext)
			|| QFile::exists(nn+".desktop"))
		    n++;
		that->mFile = nn;
	    }
	    that->mLinkFile = that->mFile+".desktop";
	    that->mFile += ext;
	}
	prepareDirectories(that->mFile);
	if ( !that->mFile.isEmpty() ) {
	    QFile f(that->mFile);
	    if ( !f.open(IO_WriteOnly) )
		that->mFile = QString::null;
	    return that->mFile;
	}
    }
    return mFile;
}

/*!
  Returns the desktop file corresponding to this AppLnk.

  \sa file() exec() name()
*/
QString AppLnk::linkFile() const
{
    if ( mLinkFile.isNull() ) {
	AppLnk* that = (AppLnk*)this;
	if ( type().contains('/') ) {
	    StorageInfo storage;
	    const FileSystem *fs = storage.fileSystemOf( that->mFile );
            /* tmpfs + and ramfs are available too but not removable
             * either we fix storage or add this
             */
	    if ( fs && ( fs->isRemovable() || fs->disk() == "/dev/mtdblock6" || fs->disk() == "tmpfs") ) {
		that->mLinkFile = fs->path();
	    } else
		that->mLinkFile = getenv( "HOME" );
	    that->mLinkFile += "/Documents/"+type()+"/"+safeFileName(that->mName);

            /* the desktop file exists make sure we don't point to the same file */
	    if ( QFile::exists(that->mLinkFile+".desktop") ) {
                AppLnk lnk( that->mLinkFile + ".desktop" );

                /* the linked is different */
                if(that->file() != lnk.file() ) {
                    int n = 1;
                    QString nn;
                    while (QFile::exists((nn=that->mLinkFile+"_"+QString::number(n))+".desktop")) {
                        n++;
                        /* just to be sure */
                        AppLnk lnk(nn );
                        if (lnk.file() == that->file() )
                            break;
                    }
                    that->mLinkFile = nn;
                }
	    }
	    that->mLinkFile += ".desktop";
	    storeLink();
	}
	return that->mLinkFile;
    }
    return mLinkFile;
}

/*!
  Copies \a copy.
*/
AppLnk::AppLnk( const AppLnk &copy )
{
    mName = copy.mName;
    mPixmap = copy.mPixmap;
    mBigPixmap = copy.mBigPixmap;
    mExec = copy.mExec;
    mType = copy.mType;
    mRotation = copy.mRotation;
    mComment = copy.mComment;
    mFile = copy.mFile;
    mLinkFile = copy.mLinkFile;
    mIconFile = copy.mIconFile;
    mMimeTypes = copy.mMimeTypes;
    mMimeTypeIcons = copy.mMimeTypeIcons;
    mId = 0;
    d = new AppLnkPrivate();
    d->mCat = copy.d->mCat;
    d->mCatList = copy.d->mCatList;
    d->mPixmaps = copy.d->mPixmaps;
}

/*!
  Destroys the AppLnk. Note that if the AppLnk is currently a member
  of an AppLnkSet, this will produce a run-time warning.

  \sa AppLnkSet::add() AppLnkSet::remove()
*/
AppLnk::~AppLnk()
{
    if ( mId )
	qWarning("Deleting AppLnk that is in an AppLnkSet");
    if ( d )
	delete d;
}

/*!
  \overload
  Executes the application associated with this AppLnk.

  \sa exec()
*/
void AppLnk::execute() const
{
    execute(QStringList());
}

/*!
  Executes the application associated with this AppLnk, with
  \a args as arguments.

  \sa exec()
*/
void AppLnk::execute(const QStringList& args) const
{
#ifdef Q_WS_QWS
    if ( !mRotation.isEmpty() ) {
	// ######## this will only work in the server
	int rot = QPEApplication::defaultRotation();
	rot = (rot+mRotation.toInt())%360;
	QCString old = getenv("QWS_DISPLAY");
	setenv("QWS_DISPLAY", QString("Transformed:Rot%1:0").arg(rot), 1);
	invoke(args);
	setenv("QWS_DISPLAY", old.data(), 1);
    } else
#endif
	invoke(args);
}

/*!
  Invokes the application associated with this AppLnk, with
  \a args as arguments. Rotation is not taken into account by
  this function, so you should not call it directly.

  \sa execute()
*/
void AppLnk::invoke(const QStringList& args) const
{
    Global::execute( exec(), args[0] );
}

/*!
  Sets the Exec property to \a exec.

  \sa exec() name()
*/
void AppLnk::setExec( const QString& exec )
{
    mExec = exec;
}

#if 0 // this was inlined for better BC
/*!
  Sets the Rotation property to \a rot.

  \sa rotation()
*/
void AppLnk::setRotation ( const QString &rot )
{
	mRotation = rot;
}
#endif

/*!
  Sets the Name property to \a docname.

  \sa name()
*/
void AppLnk::setName( const QString& docname )
{
    mName = docname;
}

/*!
  Sets the File property to \a filename.

  \sa file() name()
*/
void AppLnk::setFile( const QString& filename )
{
    mFile = filename;
}

/*!
  Sets the LinkFile property to \a filename.

  \sa linkFile()
*/
void AppLnk::setLinkFile( const QString& filename )
{
    mLinkFile = filename;
}

/*!
  Sets the Comment property to \a comment.

  This text is displayed in the 'Details Dialog', for example if the
  user uses the 'press-and-hold' gesture.

  \sa comment()
*/
void AppLnk::setComment( const QString& comment )
{
    mComment = comment;
}

/*!
  Sets the Type property to \a type.

  For applications, games and settings the type should be \c
  Application; for documents the type should be the document's MIME
  type.

  \sa type()
*/
void AppLnk::setType( const QString& type )
{
    mType = type;
}

/*!
  \fn QString AppLnk::icon() const

  Returns the Icon property.

  \sa setIcon()
*/

/*!
  Sets the Icon property to \a iconname. This is the filename from
  which the pixmap() and bigPixmap() are obtained.

  \sa icon() setSmallIconSize() setBigIconSize()
*/
void AppLnk::setIcon( const QString& iconname )
{
    mIconFile = iconname;
    QImage unscaledIcon = Resource::loadImage( mIconFile );
    d->mPixmaps[0].convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) );
    d->mPixmaps[1].convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) );
}

/*!
  Sets the Categories property to \a c.

  See the CategoryWidget for more details.

  \sa categories()
*/
void AppLnk::setCategories( const QArray<int>& c )
{
    d->mCat = c;
    d->updateCatListFromArray();
}

/*!
  \fn QStringList AppLnk::mimeTypeIcons() const

  Returns the MimeTypeIcons property of the AppLnk.
*/

/*!
  Attempts to ensure that the link file for this AppLnk exists,
  including creating any required directories. Returns TRUE if
  successful; otherwise returns FALSE.

  You should not need to use this function.
*/
bool AppLnk::ensureLinkExists() const
{
    QString lf = linkFile();
    return prepareDirectories(lf);
}

/*!
  Commits the AppLnk to disk. Returns TRUE if the operation succeeded;
  otherwise returns FALSE.

  In addition, the "linkChanged(QString)" message is sent to the
  "QPE/System" \link qcop.html QCop\endlink channel.
*/
bool AppLnk::writeLink() const
{
    // Only re-writes settable parts
    QString lf = linkFile();
    if ( !ensureLinkExists() )
	return FALSE;
    storeLink();
    return TRUE;
}

/*!
  \internal
*/
void AppLnk::storeLink() const
{
    Config config( mLinkFile, Config::File );
    config.setGroup("Desktop Entry");
    config.writeEntry("Name",mName);
    if ( !mIconFile.isNull() ) config.writeEntry("Icon",mIconFile);
    config.writeEntry("Type",type());
    if(!rotation().isEmpty())
	config.writeEntry("Rotation",rotation());
    else
	config.removeEntry("Rotation");    
    if ( !mComment.isNull() ) config.writeEntry("Comment",mComment);
    QString f = file();
    int i = 0;
    while ( i < (int)f.length() && i < (int)mLinkFile.length() && f[i] == mLinkFile[i] )
	i++;
    while ( i && f[i] != '/' )
	i--;
    // simple case where in the same directory
    if ( mLinkFile.find( '/', i + 1 ) < 0 )
	f = f.mid(i+1);
    // ### could do relative ie ../../otherDocs/file.doc
    config.writeEntry("File",f);
    config.writeEntry( "Categories", d->mCatList, ';' );

#ifndef QT_NO_COP
    QCopEnvelope e("QPE/System", "linkChanged(QString)");
    e << mLinkFile;
#endif
}

/*!
  Sets the property named \a key to \a value.

  \sa property()
*/
void AppLnk::setProperty(const QString& key, const QString& value)
{
    if ( ensureLinkExists() ) {
	Config cfg(linkFile(), Config::File);
	cfg.writeEntry(key,value);
    }
}

/*!
  Returns the property named \a key.

  \sa setProperty()
*/
QString AppLnk::property(const QString& key) const
{
    QString lf = linkFile();
    if ( !QFile::exists(lf) )
	return QString::null;
    Config cfg(lf, Config::File);
    return cfg.readEntry(key);
}

bool AppLnk::isPreloaded() const {
  // Preload information is stored in the Launcher config in v1.5.
  Config cfg("Launcher");
  cfg.setGroup("Preload");
  QStringList apps = cfg.readListEntry("Apps",',');
  if (apps.contains(exec()))
    return true;
  return false;
}

void AppLnk::setPreloaded(bool yesNo) {
  // Preload information is stored in the Launcher config in v1.5.
  Config cfg("Launcher");
  cfg.setGroup("Preload");
  QStringList apps = cfg.readListEntry("Apps", ',');
  if (apps.contains(exec()) && !yesNo)
    apps.remove(exec());
  else if (yesNo && !apps.contains(exec()))
    apps.append(exec());
  cfg.writeEntry("Apps", apps, ',');
}


/*!
  Deletes both the linkFile() and the file() associated with this AppLnk.

  \sa removeLinkFile()
*/
void AppLnk::removeFiles()
{
    bool valid = isValid();
    if ( !valid || !linkFileKnown() || QFile::remove(linkFile()) ) {
	if ( QFile::remove(file()) ) {
#ifndef QT_NO_COP
	    QCopEnvelope e("QPE/System", "linkChanged(QString)");
	    if ( linkFileKnown() )
		e << linkFile();
	    else
		e << file();
#endif
	} else if ( valid ) {
	    // restore link
	    writeLink();
	}
    }
}

/*!
  Deletes the linkFile(), leaving any file() untouched.

    \sa removeFiles()
*/
void AppLnk::removeLinkFile()
{
    if ( isValid() && linkFileKnown() && QFile::remove(linkFile()) ) {
#ifndef QT_NO_COP
	QCopEnvelope e("QPE/System", "linkChanged(QString)");
	e << linkFile();
#endif
    }
}

class AppLnkSetPrivate {
public:
    AppLnkSetPrivate()
    {
	typPix.setAutoDelete(TRUE);
	typPixBig.setAutoDelete(TRUE);
	typName.setAutoDelete(TRUE);
    }

    QDict<QPixmap> typPix;
    QDict<QPixmap> typPixBig;
    QDict<QString> typName;
};

/*!
  \class AppLnkSet applnk.h
  \brief The AppLnkSet class is a set of AppLnk objects.
*/

/*!
  \fn QStringList AppLnkSet::types() const

  Returns the list of \link applnk.html#Types types\endlink in the set.

    For applications, games and settings the type is \c Application;
    for documents the type is the document's MIME type.

  \sa AppLnk::type(), typeName(), typePixmap(), typeBigPixmap()
*/

/*!
  \fn const QList<AppLnk>& AppLnkSet::children() const

  Returns the members of the set.
*/

/*!
  Constructs an empty AppLnkSet.
*/
AppLnkSet::AppLnkSet() :
    d(new AppLnkSetPrivate)
{
}

/*!
  Constructs an AppLnkSet that contains AppLnk objects representing
  all the files in the given \a directory (and any subdirectories
  recursively).

  \omit
  The directories may contain ".directory" files which override
  any AppLnk::type() values for AppLnk objects found in the directory.
  This allows simple localization of application types.
  \endomit
*/
AppLnkSet::AppLnkSet( const QString &directory ) :
    d(new AppLnkSetPrivate)
{
    QDir dir( directory );
    mFile = directory;
    findChildren(directory,QString::null,QString::null);
}

/*!
  Detaches all AppLnk objects from the set. The set become empty and
  the caller becomes responsible for deleting the AppLnk objects.
*/
void AppLnkSet::detachChildren()
{
    QListIterator<AppLnk> it( mApps );
    for ( ; it.current(); ) {
	AppLnk* a = *it;
	++it;
	a->mId = 0;
    }
    mApps.clear();
}

/*!
  Destroys the set, deleting all the AppLnk objects it contains.

  \sa detachChildren()
*/
AppLnkSet::~AppLnkSet()
{
    QListIterator<AppLnk> it( mApps );
    for ( ; it.current(); ) {
	AppLnk* a = *it;
	++it;
	a->mId = 0;
	delete a;
    }
    delete d;
}

void AppLnkSet::findChildren(const QString &dr, const QString& typ, const QString& typName, int depth)
{
    depth++;
    if ( depth > 10 )
	return;

    QDir dir( dr );
    QString typNameLocal = typName;

    if ( dir.exists( ".directory" ) ) {
	Config config( dr + "/.directory", Config::File );
	config.setGroup( "Desktop Entry" );
	typNameLocal = config.readEntry( "Name", typNameLocal );
	if ( !typ.isEmpty() ) {
	    QString iconFile = config.readEntry( "Icon", "AppsIcon" );
	    QImage unscaledIcon = Resource::loadImage( iconFile );
	    QPixmap pm, bpm;
	    pm.convertFromImage( unscaledIcon.smoothScale( smallSize, smallSize ) );
	    bpm.convertFromImage( unscaledIcon.smoothScale( bigSize, bigSize ) );
	    d->typPix.insert(typ, new QPixmap(pm));
	    d->typPixBig.insert(typ, new QPixmap(bpm));
	    d->typName.insert(typ, new QString(typNameLocal));
	}
    }

    const QFileInfoList *list = dir.entryInfoList();
    if ( list ) {
	QFileInfo* fi;
	bool cadded=FALSE;
	for ( QFileInfoListIterator it(*list); (fi=*it); ++it ) {
	    QString bn = fi->fileName();
	    if ( bn[0] != '.' && bn != "CVS" ) {
		if ( fi->isDir() ) {
		    QString c = typ.isNull() ? bn : typ+"/"+bn;
		    QString d = typNameLocal.isNull() ? bn : typNameLocal+"/"+bn;
		    findChildren(fi->filePath(), c, d, depth );
		} else {
		    if ( fi->extension(FALSE) == "desktop" ) {
			AppLnk* app = new AppLnk( fi->filePath() );
#ifdef QT_NO_QWS_MULTIPROCESS
			if ( !Global::isBuiltinCommand( app->exec() ) )
			    delete app;
			else
#endif
			{
			    if ( !typ.isEmpty() ) {
				if ( !cadded ) {
				    typs.append(typ);
				    cadded = TRUE;
				}
				app->setType(typ);
			    }
			    add(app);
			}
		    }
		}
	    }
	}
    }
}

/*!
  Adds AppLnk \a f to the set. The set takes responsibility for
  deleting \a f.

  \sa remove()
*/
void AppLnkSet::add( AppLnk *f )
{
    if ( f->mId == 0 ) {
	AppLnk::lastId++;
	f->mId = AppLnk::lastId;
	mApps.append( f );
    } else {
	qWarning("Attempt to add an AppLnk twice");
    }
}

/*!
  Removes AppLnk \a f to the set. The caller becomes responsible for
  deleting \a f. Returns TRUE if \a f was in the set; otherwise
  returns FALSE.

  \sa add()
*/
bool AppLnkSet::remove( AppLnk *f )
{
    if ( mApps.remove( f ) ) {
	f->mId = 0;
	return TRUE;
    }
    return FALSE;
}


/*!
  Returns the localized name for type \a t.

    For applications, games and settings the type is \c Application;
    for documents the type is the document's MIME type.
*/
QString AppLnkSet::typeName( const QString& t ) const
{
    QString *st = d->typName.find(t);
    return st ? *st : QString::null;
}

/*!
  Returns the small pixmap associated with type \a t.

    For applications, games and settings the type is \c Application;
    for documents the type is the document's MIME type.
*/
QPixmap AppLnkSet::typePixmap( const QString& t ) const
{
    QPixmap *pm = d->typPix.find(t);
    return pm ? *pm : QPixmap();
}

/*!
  Returns the large pixmap associated with type \a t.

    For applications, games and settings the type is \c Application;
    for documents the type is the document's MIME type.
*/
QPixmap AppLnkSet::typeBigPixmap( const QString& t ) const
{
    QPixmap *pm = d->typPixBig.find(t);
    return pm ? *pm : QPixmap();
}

/*!
  Returns the AppLnk with the given \a id.
*/
const AppLnk *AppLnkSet::find( int id ) const
{
    QListIterator<AppLnk> it( children() );

    for ( ; it.current(); ++it ) {
	const AppLnk *app = it.current();
	if ( app->id() == id )
	    return app;
    }

    return 0;
}

/*!
  Returns the AppLnk with the given \a exec attribute.
*/
const AppLnk *AppLnkSet::findExec( const QString& exec ) const
{
    QListIterator<AppLnk> it( children() );

    for ( ; it.current(); ++it ) {
	const AppLnk *app = it.current();
	if ( app->exec() == exec )
	    return app;
    }

    return 0;
}

/*!
  \class DocLnkSet applnk.h
  \brief The DocLnkSet class is a set of DocLnk objects.
*/

/*!
  \fn const QList<DocLnk>& DocLnkSet::children() const

  Returns the members of the set.
*/

/*!
  Constructs an empty DocLnkSet.

  \sa appendFrom()
*/
DocLnkSet::DocLnkSet()
{
}

/*!
  Constructs a DocLnkSet that contains DocLnk objects representing all
  the files in the \a directory (and any subdirectories, recursively).

  If \a mimefilter is not null,
  only documents with a MIME type matching \a mimefilter are selected.
  The value may contain multiple wild-card patterns separated by ";",
  such as \c{*o/mpeg;audio/x-wav}.

  See also \link applnk.html#files-and-links Files and Links\endlink.

*/
DocLnkSet::DocLnkSet( const QString &directory, const QString& mimefilter ) :
    AppLnkSet()
{
    QDir dir( directory );
    mFile = dir.dirName();
    QDict<void> reference;

    QStringList subFilter = QStringList::split(";", mimefilter);
    QValueList<QRegExp> mimeFilters;
    for( QStringList::Iterator it = subFilter.begin(); it != subFilter.end(); ++ it )
	mimeFilters.append( QRegExp(*it, FALSE, TRUE) );

    findChildren(directory, mimeFilters, reference);

    const QList<DocLnk> &list = children();
    for ( QListIterator<DocLnk> it( list ); it.current(); ++it ) {
	reference.remove( (*it)->file() );
    }

    for ( QDictIterator<void> dit(reference); dit.current(); ++dit ) {
	if ( dit.current() == (void*)2 ) {
	    // Unreferenced, make an unwritten link
	    DocLnk* dl = new DocLnk;
	    QFileInfo fi( dit.currentKey() );
	    dl->setFile(fi.filePath());
	    dl->setName(fi.baseName());
	    // #### default to current path?
	    // dl->setCategories( ... );
	    bool match = mimefilter.isNull();
	    if ( !match )
		for( QValueList<QRegExp>::Iterator it = mimeFilters.begin(); it != mimeFilters.end() && !match; ++ it )
		    if ( (*it).match(dl->type()) >= 0 )
			match = TRUE;
	    if ( match /* && dl->type() != "application/octet-stream" */
		    && !!dl->exec() )
		add(dl);
	    else
		delete dl;
	}
    }
}

// other becomes empty
/*!
  Transfers all DocLnk objects from \a other to this set. \a other becomes
  empty.
*/
void DocLnkSet::appendFrom( DocLnkSet& other )
{
    if ( &other == this )
	return;
    QListIterator<AppLnk> it( other.mApps );
    for ( ; it.current(); ) {
	mApps.append(*it);
	++it;
    }
    other.mApps.clear();
}

void DocLnkSet::findChildren(const QString &dr, const QValueList<QRegExp> &mimeFilters, QDict<void> &reference, int depth)
{
    depth++;
    if ( depth > 10 )
	return;

    QDir dir( dr );

    /* Opie got a different approach
     * I guess it's geek vs. consumer
     * in this case to be discussed
     */
    if ( dir.exists( ".Qtopia-ignore" ) )
	return;

    const QFileInfoList *list = dir.entryInfoList();
    if ( list ) {
	QFileInfo* fi;
	for ( QFileInfoListIterator it(*list); (fi=*it); ++it ) {
	    QString bn = fi->fileName();
	    if ( bn[0] != '.' ) {
		if ( fi->isDir()  ) {
		    if ( bn != "CVS" && bn != "Qtopia" && bn != "QtPalmtop" )
			findChildren(fi->filePath(), mimeFilters, reference, depth);
		} else {
		    if ( fi->extension(FALSE) == "desktop" ) {
			DocLnk* dl = new DocLnk( fi->filePath() );
			QFileInfo fi2(dl->file());
			bool match = FALSE;
			if ( !fi2.exists() ) {
			    dir.remove( dl->file() );
			}
			if ( mimeFilters.count() == 0 ) {
			    add( dl );
			    match = TRUE;
			} else {
			    for( QValueList<QRegExp>::ConstIterator it = mimeFilters.begin(); it != mimeFilters.end(); ++ it ) {
				if ( (*it).match(dl->type()) >= 0 ) {
				    add(dl);
				    match = TRUE;
				}
			    }
			}
			if ( !match )
			    delete dl;
		    } else {
			if ( !reference.find(fi->fileName()) )
			    reference.insert(fi->filePath(), (void*)2);
		    }
		}
	    }
	}
    }
}

/*!
  \class DocLnk applnk.h
  \brief The DocLnk class represents loaded document references.
*/

/*!
  \fn DocLnk::DocLnk( const DocLnk &o )

  Copies \a o.
*/

/*!
  Constructs a DocLnk from a valid .desktop \a file or a new .desktop
  \a file for other files.
*/
DocLnk::DocLnk( const QString &file ) :
    AppLnk(file)
{
    init(file);
}

/*!
  Constructs a DocLnk from a valid .desktop \a file or a new .desktop
  \a file for other files. If \a may_be_desktopfile is TRUE, then an
  attempt is made to read \a file as a .desktop file; if that fails it
  is read as a normal file.
*/
DocLnk::DocLnk( const QString &file, bool may_be_desktopfile ) :
    AppLnk(may_be_desktopfile ? file : QString::null)
{
    init(file);
}

void DocLnk::init(const QString &file)
{
    if ( isValid() ) {
#ifndef FORCED_DIR_STRUCTURE_WAY
	if ( mType.isNull() )
	    // try to infer it
#endif
	{
	    int s0 = file.findRev('/');
	    if ( s0 > 0 ) {
		int s1 = file.findRev('/',s0-1);
		if ( s1 > 0 ) {
		    int s2 = file.findRev('/',s1-1);
		    if ( s2 > 0 ) {
			mType = file.mid(s2+1,s0-s2-1);
		    }
		}
	    }
	}
    } else if ( QFile::exists(file) ) {
	QString n = file;
	n.replace(QRegExp(".*/"),"");
	n.replace(QRegExp("\\..*"),"");
	setName( n );
	setFile( file );
    }
    MimeType mt(mType);
    if( mt.application() )
	mExec = mt.application()->exec();
}

/*!
  Constructs an invalid DocLnk.
*/
DocLnk::DocLnk()
{
}

/*!
  Destroys the DocLnk. Just like AppLnk objects, a run-time error
  occurs if the DocLnk is a member of a DocLnkSet (or AppLnkSet).
*/
DocLnk::~DocLnk()
{
}

/*!
  \reimp
*/
QString DocLnk::exec() const
{
    MimeType mt(type());
    const AppLnk* app = mt.application();
    if ( app )
	return app->exec();
    else
	return QString::null;
}

/*!
  \reimp
*/
void DocLnk::invoke(const QStringList& args) const
{
    MimeType mt(type());
    const AppLnk* app = mt.application();
    if ( app ) {
	QStringList a = args;
	if ( linkFileKnown() && QFile::exists( linkFile() ) )
	    a.append(linkFile());
	else
	    a.append(file());
	app->execute(a);
    }
}